#include <stdio.h>
int main()
{
short int i = 20;
char c = 97;
printf("%d, %d, %d\n", sizeof(i), sizeof(c), sizeof(c + i));
return 0;
}
Could some one tell me what happens when sizeof(a+b) "a is short int type & b is char type" Output is : 2, 1, 4
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
).
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
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With