![]() |
VOOZH | about |
Every literal (constant) in C/C++ will have a type of information associated with it. In both C and C++, numeric literals (e.g. 10) will have int as their type. It means sizeof(10) and sizeof(int) will return the same value.
If we compile what we have said in terms of code then it will look something like this.
Example:
Output:
4 4
However, character literals (e.g. 'V') will have different types, sizeof('V') returns different values in C and C++. In C, a character literal is treated as int type whereas, in C++, a character literal is treated as char type (sizeof('V') and sizeof(char) are the same in C++ but not in C. Let us see this interesting behaviour through an example.
Result of above program:
More precisely we can say that in C, sizeof('V') will be treated as long unsigned int, let us see an example to make things more clear.
Output: it will give this error.
source.c: In function 'main':
source.c:7:10: warning: format '%d' expects argument of type 'int', but argument 2 has type 'long unsigned int' [-Wformat=]
7 | printf("%d", sizeof('V'));
| ~^ ~~~~~~~~~~~
| | |
| int long unsigned int
| %ld
Such behavior is required in C++ to support function overloading. An example will make it more clear. Predict the output of the following C++ program.
Output:
From foo: char
The compiler must call
void foo(char);
since 'V' type is char.