I found strange from my point of view compiler behavior, It allows assign Boolean value to * char
.
char * k= false;
Why? But after assignment * char is still not initialized. Why compilers doesn't allows assign int
value?
I found strange from my point of view compiler behavior, It allows assign Boolean value to * char
.
char * k= false;
Why? But after assignment * char is still not initialized. Why compilers doesn't allows assign int
value?
It will be implicitly converting the boolean value false
to an integer with value zero and as such declaring a NULL pointer. It is effectively no different from
char* k = 0;
which is valid syntax
C++03 Standard, #4.10:
A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero.
5.19:
An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type tem- plate parameters of integral or enumeration types, and sizeof expressions.
false
is a boolean literal, therefore it falls into the category of a constant expression, so it can qualify as a null pointer constant.
false
and true
are shortcuts for 0
and 1
. For pointer you use NULL
which define NULL 0
. So it correct syntax.
The compiler allows it because in C++ false
is the same as 0
and NULL
.
Personally, at least for assignments, I find it easier to understand and more correct to use NULL
to indicate a null pointer.
Btw, before C++, on some systems NULL
was actually a macro defined as (void*)0xffff
; some background on that can be found in this answer.