I'm wondering if anyone can explain the following to me: If I write
int i = 0;
float* pf = i;
I get a compile error (gcc 4.2.1):
error: invalid conversion from ‘int’ to ‘float*’
Makes sense - they are obviously two completely different types. But if instead I write
const int i = 0;
float* pf = i;
It compiles without error. Why should the 'const' make a difference on the right hand side of the assignment? Isn't part of the idea of the 'const' keyword to be able to enforce type constraints for constant values?
Any explanation I have been able to come up with feels kind of bogus. And none of my explanations also explain the fact that
const int i = 1;
float* pf = i;
fails to compile. Can anyone offer an explanation?
We declare a pointer to constant. First, we assign the address of variable 'a' to the pointer 'ptr'. Then, we assign the address of variable 'b' to the pointer 'ptr'. Lastly, we try to print the value of 'ptr'.
We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const). We can also create a constant pointer to a constant in C, which means that neither the value of the pointer nor the value of the variable pointed to by the pointer would change.
In the pointers to constant, the data pointed by the pointer is constant and cannot be changed. Although, the pointer itself can change and points somewhere else (as the pointer itself is a variable).
Pointer to constant As the name itself indicates, the value of the variable to which the pointer is pointing, is constant. In other words, a pointer through which one cannot change the value of the variable to which it points is known as a pointer to constant.
Your second example simply happens to be covered by the conversion rules as specified in §4.10/1 (C++03):
A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of pointer to object or pointer to function type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With