views:

93

answers:

1

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?

+8  A: 

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.

Georg Fritzsche