Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different outputs of sizeof operator in C and C++

Tags:

c++

c

sizeof

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:

  • Why are the outputs different?
  • Is sizeof independent of the OS or compiler?
  • Is it dependent on language?
like image 974
msc Avatar asked Aug 11 '17 11:08

msc


1 Answers

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 yields 1 if the specified relation is true and 0 if it is false. The result has type int.

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 type std::nullptr_t. The operators == and != both yield true or false, i.e., a result of type bool.

Therefore, the sizeof(1 == 1) will return equal value to sizeof(bool) which is implementation defined and in your case it is 1.

like image 126
Akira Avatar answered Oct 01 '22 12:10

Akira