I found a bug in my code where I compared the pointer with ‘\0’.
Wondering why the compiler didn’t warn me about this bug I tried the following.
#include <cassert>
struct Foo
{
char bar[5];
};
int main()
{
Foo f;
Foo* p = &f;
p->bar[0] = '\0';
assert(p->bar == '\0'); // #1. I forgot [] Now, comparing pointer with NULL and fails.
assert(p->bar == 'A'); // #2. error: ISO C++ forbids comparison between pointer and integer
assert(p->bar[0] == '\0'); // #3. What I intended, PASSES
return 0;
}
What is special about ‘\0’ which makes #1 legal and #2 illegal?
Please add a reference or quotation to your answer.
What makes it legal and well defined is the fact that
'\0'is a null pointer constant so it can be converted to any pointer type to make a null pointer value.ISO/IEC 14882:2011 4.10 [conv.ptr] / 1:
'\0'meets the requirements of “integral constant expression prvalue of integer type that evaluates to zero” becausecharis an integer type and\0has the value zero.Other integers can only be explicitly converted to a pointer type via a
reinterpret_castand the result is only meaningful if the integer was the result of converting a valid pointer to an integer type of sufficient size.