Search code examples
c++csizeofprimitive-types

Why do we get different results/outputs on different compilers?


#include <stdio.h>
int main () {
    double num = 5.2;
    int var = 5;
    printf("%d\t", sizeof(!num));
    printf("%d\t", sizeof(var = 15/2));
    printf("%d", var);
    return 0;
}

Running this program on VS 2010 and GCC 4.7.0 gives the output as 1 4 5 and using Turbo 3.0/4.5 gives 2 4 5 as the result.

From where can we get the exact sizes of the datatypes ?

I did read the following links:link1, link2, link3, link4 and link5 But they were not able to answer my query !


Solution

  • This question is a complicated way to ask why sizeof(bool) is 1 in some compilers and 2 in others. And indeed, the C++ standard does not require the size of bool to be 1, which means that different compilers may allocate a different size for it, and this is the answer to your question.

    As for why it doesn't require it to be 1, take a look at this related question about sizeof(bool).

    If you are not clear why bool is involved here at all, it's because you invoke the ! operator on a double value, which is the equivalent of checking if it's non-zero, and such a check returns a bool. The other two prints are basically sizeof(int) (because int / int is an int itself) and the value of an integer.