How does sizeof work for different data types when added and calculated? [duplicate]

StackOverflow https://stackoverflow.com/questions/21339887

  •  02-10-2022
  •  | 
  •  

Question

#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;
}

The output of this code is

2, 1, 4

According to me it should be

2, 1, 2

because char + short int is short int and size of short int is 2.

Was it helpful?

Solution

According to C standard integral promotion rules, the type of the expression c + i will be int, that's why you're getting the equivalent of sizeof (int), i.e. 4.

When different arithmetic types are used as operands in certain types of expressions, standard conversions known as usual arithmetic conversions are applied. These conversions are applied according to the rank of the arithmetic type: the operand with a type of lower rank is converted to the type of the operand with a higher rank. This is known as integral or floating point promotion.

enter image description here

Besides this, according to here, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied. So you will get 4 even for sizeof(c+c).

And you can find the following information from This International Standard - Programming languages — C, Section 6.3.1.1, Clause 2:

[...] If an intcan represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. The integer promotions are applied only: as part of the usual arithmetic conversions, to certain argument expressions, to the operands of the unary +, -, and ~operators, and to both operands of the shift operators, as specified by their respective subclauses.) [...]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top