Different outputs of sizeof() operator in C and C++.
In C:
int main()
{
printf("%zu\n", sizeof(1 == 1));
return 0;
}
output:
4
In C++:
int main()
{
std::cout << sizeof(1 == 1) << std::endl;
return 0;
}
output:
1
Questions:
sizeof independent of the OS or compiler?According to N1570 draft (c11):
6.5.9 Equality operators
The
==(equal to) and!=(not equal to) operators are analogous to the relational operators except for their lower precedence. Each of the operators yields1if the specified relation is true and0if it is false. The result has typeint.
Therefore, the sizeof(1 == 1) will return equal value to sizeof(int) which is implementation defined and in your case it is 4.
According to N4296 draft (c++14):
5.10 Equality operators
The
==(equal to) and the!=(not equal to) operators group left-to-right. The operands shall have arithmetic, enumeration, pointer, or pointer to member type, or typestd::nullptr_t. The operators==and!=both yieldtrueorfalse, i.e., a result of typebool.
Therefore, the sizeof(1 == 1) will return equal value to sizeof(bool) which is implementation defined and in your case it is 1.
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