简体   繁体   中英

Different outputs of sizeof operator in C and C++

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?

According to N1570 draft ( ):

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 ( ):

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 , ie, 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 .

In C result of == and != operators is int

According to N1570 draft - 6.5.9 Equality operators

4 means sizeof(int) , but it depends on architecture.


In C++ result of == and != operators is bool

According to N4296 draft - 5.10 Equality operators

1 means sizeof(bool) the size cannot be smaller than one byte. But it would be legal to be larger than one byte.

Because the type of the result in C is int (and 4 bytes is a typical size) and in C++ it's bool (and 1 is the typical size for that).

These values are implementation dependent.

Here's a C11 program that demonstrates that using _Generic (typical output int 4 ):

#include <stdio.h>

void what_int(){
    printf("int %lu",sizeof(int));
}

void what_other(){
    printf("other ?");
}

#define what(x) _Generic((x), \
    int : what_int(),\
    default: what_other()\
)

int main(void) {

    what(1==1);

    return 0;
}

Here's a C++ program that demonstrates that using template specializaton (typical output bool 1 ):

#include <iostream>

template<typename T>
void what(T x){
   std::cout<<"other "<<sizeof(T);
}

template<>
void what(bool x){
   std::cout<<"bool "<<sizeof(bool);
}


int main(){
    what(1==1);
    return 0;
}

I can't readily think of any code that is both C and C++ that would have a different outcome. Please accept that as a challenge.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM