Assigning a pointer variable to a const int in C++?
- by John
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?