Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof operator returns 4 for (char + short ) [duplicate]

Tags:

c

Given this code snippet:

    #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 is sizeof(c + i) == 4?

like image 251
duslabo Avatar asked Jul 19 '13 10:07

duslabo


People also ask

Why does sizeof return 4?

Operands of type char are promoted to type int and the actual addition is performed within the domain of int (or unsigned int , depending on the properties of char on that platform). So your a + b is actually interpreted as (int) a + (int) b . The result has type int and sizeof(int) is apparently 4 on your platform.

What does sizeof return char?

The sizeof keyword refers to an operator that works at compile time to report on the size of the storage occupied by a type of the argument passed to it (equivalently, by a variable of that type). That size is returned as a multiple of the size of a char, which on many personal computers is 1 byte (or 8 bits).

What does sizeof operator return in C?

If an unsized array is the last element of a structure, the sizeof operator returns the size of the structure without the array. buffer = calloc(100, sizeof (int) ); This example uses the sizeof operator to pass the size of an int , which varies among machines, as an argument to a run-time function named calloc .

What is sizeof () operator give an example?

The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.


1 Answers

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

like image 138
Ingo Leonhardt Avatar answered Oct 02 '22 19:10

Ingo Leonhardt