Sizeof integer expression in C

To my half success with Xcode compiling C (gnu11)

#include <stdio.h>
int main(int argc,char**argv)
{
    short s = 1;
    printf( "%zd %zd %zd\n", sizeof(s), sizeof(s*s), sizeof(s?s:s));
    return 0;
}

Outputs

2 4 4

I expected

2 2 2

or maybe

2 4 2

Why is this?

+3
source share
3 answers

I recalled from K & R that any integer expression smaller than int is promoted to int. I found this in Standard (C89) :

3.2.1.1 Symbols and Integers

A char, a short int or int bit-field, or their signed or unsigned varieties or an object that has an enumeration type, can be used in an expression wherever int or unsigned int can be used. If int can represent all values โ€‹โ€‹of the original type, the value is equally converted to int;

, s? s: s, , , , - lvalue, ++. C rvalue. , ++:

2 4 2

r. C ++.

+7

, sizeof . C , , int, int . , s * s int, int, int.

short ? short : short int ? int : int.

+5

C11ยง6.5.15/5:

, , , , , . [...]

In your case, the result is equal sizeof(int), because 'ordinary arithmetic conversions support shortup to ints. The same as with sizeof(s*s).

+4
source

Source: https://habr.com/ru/post/1686389/


All Articles