The sizeof operator returns 4 for (char + short)

Given this piece of code:

#include <stdio.h> int main() { short i = 20; char c = 97; printf("%d, %d, %d\n", sizeof(i), sizeof(c), sizeof(c + i)); return 0; } 

Why sizeof(c + i) == 4 ?

+7
c
source share
3 answers

c + i is an integer expression (integer promotion!), so sizeof() returns sizeof(int)

+17
source share

Integer types smaller than int are promoted when an operation is performed on them. If all values โ€‹โ€‹of the original type can be represented as int, the value of the smaller type is converted to int; otherwise, it is converted to unsigned int.

Integer stocks require the promotion of each variable (c and i) to an int size.

 short i = 20; char c = 97; //The two int values are added and the sum is truncated to fit into the char type. char a = c + i; printf("%d, %d, %d %d\n", sizeof(i), sizeof(c), sizeof(c + i),sizeof(a)); 2, 1, 4 1 
+4
source share

C uses int for all integer calculations, unless otherwise specified. On your platform, int clearly longer than 32 bits, so sizeof returns 4 . If your compiler will use 64-bit integers, it will be 8 .

+3
source share

All Articles