Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens here? sizeof(short_int_variable + char_variable)

#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

like image 504
hem Avatar asked May 07 '13 09:05

hem


3 Answers

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).

like image 171
unwind Avatar answered Nov 19 '22 10:11

unwind


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 
like image 4
Mani Avatar answered Nov 19 '22 09:11

Mani


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..

like image 1
VoidPointer Avatar answered Nov 19 '22 09:11

VoidPointer