Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value of sizeof() operator in C & C++ [duplicate]

#include<stdio.h>
int main()
{
    printf("%d", sizeof('a'));
    return 0;
}

Why does the above code produce different results when compiling in C and C++ ? In C, it prints 4 while in C++, it is the more acceptable answer i.e. 1.
When I replace the 'a' inside sizeof() with a char variable declared in main function, the result is 1 in both cases!

like image 432
mac93 Avatar asked Oct 29 '13 12:10

mac93


2 Answers

Because, and this might be shocking, C and C++ are not the same language.

C defines character literals as having type int, while C++ considers them to have type char.

This is a case where multi-character constants can be useful:

const int foo = 'foo';

That will generate an integer whose value will probably be 6713199 or 7303014 depending on the byte-ordering and the compiler's mood. In other words, multiple-character character literals are not "portable", you cannot depend on the resulting value being easy to predict.

As commenters have pointed out (thanks!) this is valid in both C and C++, it seems C++ makes multi-character character literals a different type. Clever!

Also, as a minor note that I like to mention when on topic, note that sizeof is not a function and that values of size_t are not int. Thus:

printf("the size of a character is %zu\n", sizeof 'a');

or, if your compiler is too old not to support C99:

printf("the size of a character is %lu\n", (unsigned long) sizeof 'a');

represent the simplest and most correct way to print the sizes you're investigating.

like image 146
unwind Avatar answered Oct 26 '22 09:10

unwind


In C, the 'a' is a character constant, which is treated as an integer, so you get a size of 4, whereas in C++ it's treated as a char.

possible duplicate question Size of character ('a') in C/C++

like image 40
Jitendra Avatar answered Oct 26 '22 11:10

Jitendra