Is comparing a pointer to '\0' legal?
On the trunk version of clang++ (25836be2c)
const char *a = "foo";
if(a == '\0')
gives an error: comparison between pointer and integer ('const char *' and 'int')
whereas
if(a == 0)
does not give any error as expected.
Isn't the null character equivalent to the null pointer for comparisons with pointer? Is this a compiler bug?
Another point is that this error does not show up with "-std=c++03" flag but shows up with "-std=c++11" flag. However, I don't get the error in both standards when I use g++ (v4.8.5)
This was a change from C++03 to C++14. In C++03, [conv.ptr]p1 says:
A null pointer constant is an integral constant expression rvalue of integer type that evaluates to zero.
A character literal is an integral constant expression.
In C++14, [conv.ptr]p1 says:
A null pointer constant is an integer literal with value zero or a prvalue of type std::nullptr_t.
A character literal is not an integer literal, nor of type std::nullptr_t.
The originally published version of C++11 didn't contain this change; however, it was introduced due to defect report DR903 and incorporated into the standard sometime after January 2013 (the date of the last comment on that DR).
Because the change is the result of a DR, compilers treat it as a bugfix to the existing standard, not part of the next one, and so Clang and GCC both made the behavior change when -std=c++11, not just when -std=c++14. However, apparently this change wasn't implemented in GCC until after version 4.8. (Specifically, it seems to have only been implemented in GCC 7 and up.)
From [conv.ptr]§1:
A null pointer constant is an integer literal with value zero or a prvalue of type
std::nullptr_t. [...]
'\0' is not an integer literal, it's a character literal, thus the conversion does not apply.
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