This is not a matter of recommended practise (nor undefined behavior), but about what the c++-standard actually guarantees in the matter of turning all bytes of an integer type to the value of
(unsigned char)0.
The Question(s)
In the snippet below, is the expression used by the if-statement guaranteed to be evaluated to true in c++11?
std::memset (
reinterpret_cast<char*> (&a), // int a;
(unsigned char)0,
sizeof (int)
);
if (a == 0) {
...
}
By reading the quotations from the C99 and C++11 standard (further down in this post) we find that C99 explicitly guarantees that an integer type with all bits set to 0 will represent the value 0 in that type.
I cannot find this guarantee in the C++11 standard.
- Is there no such guarantee?
- Is the result of the previous snippet really implementation-specific?
In C99 (ISO/IEC 9899:1999)
5.2.1.2/1 Multibyte characters
A byte with all bits zero shall be interpreted as a null character independent of shift state. Such a byte shall not occur as part of any other multibyte character.
6.2.6.2/1 Integer types
The values of any padding bits are unspecified.45) A valid (non-trap) object representation of a signed integer type where the sign bit is zero is a valid object representation of the corresponding unsigned type, and shall represent the same value.
For any integer type, the object representation where all the bits are zero shall be a representation of the value zero in that type.
In C++11 (ISO/IEC 14882:2011)
2.3/3 Character sets [lex.charset]
The basic execution character set and the basic execution wide-character set shall each contain all the members of the basic source character set, plus control characters representing alert, backspace, and carriage return, plus a null character (respectively, null wide character), whose representation has all zero bits.