-1

To print the size of the variables using sizeof()

#include <stdio.h>

main()
{
    int a = 10,b = 20; 
    short int c;
    short int d = sizeof(c = a+b);
    int e = sizeof(c*d); //e holds the value of 4 rather than 2
    double f = sizeof(e*f);
    printf("d:%d\ne:%d\nf:%lf\n",d,e,f);
}

Why is sizeof() returning the size of int rather than short int which is meant to be 2 bytes?

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Jaivvignesh
  • 147
  • 1
  • 2
  • 8
  • See also: [why sizeof(short + short) has different size than sizeof(short)?](https://stackoverflow.com/q/24610737/253056) – Paul R Jul 26 '17 at 11:47

1 Answers1

2

The statement

sizeof(c = a+b);

doesn't measure the size of variable c but the size of the value computed from expression c = a+b. It is the value of a+b that is assigned to c but it is also the value of the entire expression.

The integral values whose storage type is smaller than int that appear in an arithmetic expression are promoted to int (or unsigned int) for the computation. The storage type of the result of the arithmetic expression is int. This is not affected that the fact that you store it in a short int variable. Hence the value returned by sizeof().

The same for sizeof(c*d).

axiac
  • 56,918
  • 8
  • 77
  • 110