#include
int main()
{
short int i = 20;
char c = 97;
printf(\"%d, %d, %d\\n\", sizeof(i), sizeof(c), s
1) sizeof(i) ==> sizeof(short int) = 2
2) sizeof(c) ==> sizeof(char) = 1
3) sizeof(c + i [97+20]) ==> sizeof(int) = 4 // result in constant value which is int as default
Because of C's standard integral promotion rules, the type of the expression c + i
is int
, so that's why you're getting the equivalent of sizeof (int)
.
Note that sizeof
is not a function, the parenthesis are only needed when naming a type and to resolve precendence conflicts. Your code coule be written:
printf("%zu, %zu, %zu\n", sizeof i, sizeof c, sizeof (c + i));
The final use of sizeof
has parentheses since sizeof
binds tighter than +
, saying sizeof c + i
would be parsed as (sizeof c) + i
which is not the desired result.
Also note that it's a compile-time construct most of the time, the expression is never actually evaluated. All that happens is that the compiler "pretends" to evaluate it, to figure out the type of the expression, and then gives you the size of a value of that type. The actual value never needs to exist, which is sometimes neat.
The type of the value returned by sizeof
is size_t
, which is printed using %zu
(it's not int
).
The data type of a is "short int". -32768 ~ +32767
The data type of c is "char". 0 ~ 255
When you add a to c it is not either short int nor char, it becomes int!
Here is is an example code which help you to get the variable data type:
#include <typeinfo>
int main()
{
short int a = 1;
char c = 'A';
std::cout << typeid(a + c).name() << std::endl;
return 1;
}
sizeof only works at compiletime to get the size of an expression.
The following wont actually increase 'c':
c = sizeof(++c);
The expression sizeof(a + b) will return the largest type with unsigned having precedence
As others have told, sizeof is computed at compile-time.
Here, value of the expression c + i
integer, as c and i are promoted (integral promotion) to int and thus
sizeof( c + i )
gives you 4 bytes on 32-bit machine..