简体   繁体   中英

Confusion about sizeof operator in C

I'm confused about sizeof operator in C.

#include <stdio.h>

int main(void)
{
    char num1=1, num2=2, result;
    result = num1 + num2;
    printf("Size of result: %d \n",sizeof result);
    printf("Size of result: %d \n",sizeof(num1+num2));
}

The results are 1 and 4 respectively. Why does this happen?

TL;DR answer:

  • sizeof result is same as sizeof(char) .
  • sizeof(num1+ num2) is same as sizeof (int) why?

In your case, they produce 1 (guaranteed by standard) and 4 (may vary), respectively.

That said , sizeof produces a result of type size_t , so you should %zu format specifier to print the value.


Why:

First, for the addition operator + , quoting C11 , chapter §6.5.6

If both operands have arithmetic type, the usual arithmetic conversions are performed on them.

Regarding usual arithmetic conversions , §6.3.1.8/p1

[....] Otherwise, the integer promotions are performed on both operands.[...]

and then from §6.3.1.1,/p2,

If an int can 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 .

So, sizeof(num1+num2) is the same as sizeof(int) .

result is of char type, therefore sizeof is giving 1 while num1+num2 promoted to int type and therefore it gives 4 (size of int ).

Note that when an arithmetic operation is performed on a type smaller than that of int and all of it's value can be represented by int then result will be promoted to int type.

num1 + num2 is becoming integer and hence the output is 4 whereas result is char which outputs 1.

You can refer this article Integer Promotion :

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

the size of one char is 1byte, a char can hold values up to 127(unsigned up to 255). when you say something like (a + b) a temporary variable is created and used to add a to b, because a and b can hold only 127, they are promoted by the compiler to be an int, just to be sure.

which is logical because if a = 100 and b = 100, the user would like to see 200 when he adds them and not 73 (which is the result of an overflow).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM