Various outputs of the sizeof operator in C and C ++

Various operator outputs sizeof()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 different outputs?
  • Is it sizeofOS or compiler independent?
  • Does it depend on the language?
+4
source share
3 answers

According to N1570 draft ( ):

6.5.9 Equality Operators

The operators ==(equal) and !=(not equal) are similar to relational operators, except for their lower priority. Each of the operators gives 1if the indicated relation is true and 0if it is false. The result is of type int .

, sizeof(1 == 1) sizeof(int), , 4.


N4296 ():

5.10

== () != ( ) . , , std::nullptr_t. == != true false, .. bool.

, sizeof(1 == 1) sizeof(bool), , 1.

+15

C == != int

N1570 draft - 6.5.9

4 sizeof(int), .


C++ == != bool

N4296 draft - 5.10

1 sizeof(bool) . .

+14

C int ( 4 - ), ++ bool ( 1).

.

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 the specializaton pattern (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 cannot readily think of any code that is both C and C ++ that would have a different result. Take it as a challenge.

+7
source

Source: https://habr.com/ru/post/1683525/


All Articles