I was trying to understand the use of 'const' keyword with pointers from the source: GeeksforGeeks.
It is mentioned that "Passing const argument value to a non-const parameter of a function isn't valid it gives you a compile-time error."
However, *ptr, where ptr is a pointer to a constant value, did not raise an error when passed as an argument to a non-const parameter of a function.
In the following code:
#include <iostream>
using namespace std;
int content_of(int* y) { return *y; }
int same(int k){return k;}
// Functions with non-const parameters
int main()
{
int z = 8; //Non-const integer
const int *x = &z; //Pointer to constant
return 0;
}
When I pass 'x' as an argument in 'content_of':
cout << content_of(x)<<'\n';
It raises an error:
argument of type "const int *" is incompatible with parameter of type "int *"
This can be resolved by replacing int* y with const int* y. Passing &z (address of z), on the other hand, is valid as it is non-const. This agrees with the theory above.
But, when I pass *x into the function same:
cout << same(*x)<<'\n';
It gives output 8, raising no errors. Passing z, too, gave the same output and raised no errors, as expected.
It was my understanding that *x was of type const int (because, unlike z, I was not able to reassign a different value to it). Hence, it should have raised an error on being equated to a non-const int k. Why is that not the case?