j s
j s

Reputation: 307

Why is the size of the data type different when the value is directly passed to the sizeof operator?

#include <stdio.h>
int main() {
    char a = 'A';
    int b = 90000;
    float c = 6.5;
    printf("%d ",sizeof(6.5));
    printf("%d ",sizeof(90000));
    printf("%d ",sizeof('A'));
    printf("%d ",sizeof(c));
    printf("%d ",sizeof(b));
    printf("%d",sizeof(a));
    return 0;
}

The output is:

8 4 4 4 4 1

Why is the output different for the same values?

Upvotes: 17

Views: 1324

Answers (4)

Alon Alush
Alon Alush

Reputation: 1387

In C, numeric literals have default types different from their variable counterparts. For example, 6.5 is a double literal by default (so sizeof(6.5) is 8 on most platforms), while 90000 is typed as an int literal (so sizeof(90000) is 4). 'A' (in an expression context) is an int in C (4 bytes), but when stored in a char a = 'A';, its size is 1. Hence you see different sizes for what look like the “same” values.

Upvotes: 0

S.S. Anne
S.S. Anne

Reputation: 15584

Because the values don't matter to sizeof. It's the size of the types.

  • character constants are ints, not chars.

  • floating-point constants are by default doubles unless you suffix them with f or l.

Upvotes: 2

dbush
dbush

Reputation: 225827

Constants, like variables, have a type of their own:

  • 6.5 : A floating point constant of type double
  • 90000 : An integer constant of type int (if int is 32 bits) or long (if int is 16 bits)
  • 'A' : A character constant of type int in C and char in C++

The sizes that are printed are the sizes of the above types.

Also, the result of the sizeof operator has type size_t. So when printing the proper format specifier to use is %zu, not %d.

Upvotes: 21

Vlad from Moscow
Vlad from Moscow

Reputation: 311186

Character constants in C (opposite to C++) have the type int. So this call

printf("%d",sizeof('A'));

outputs 4. That is sizeof( 'A' ) is equal to sizeof( int ).

From the C Standard (6.4.4.4 Character constants)

10 An integer character constant has type int....

On the other hand (6.5.3.4 The sizeof and alignof operators)

4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

So the operand of the sizeof operator in this expression sizeof( 'A' ) has the type int while in this expression sizeof( a ) where a is declared like

char a = 'A';

the operand has the type char.

Pay attention to that calls like this

printf("%d",sizeof(6.5));

use incorrect conversion format specifier. You have to write

printf("%zu",sizeof(6.5));

Also in the above call there is used a constant of the type double while in this call

printf("%zu",sizeof(c));

the variable c has the type float.

You could get the same result for these calls if the first call used a constant of the type float like

printf("%zu",sizeof(6.5f));

Upvotes: 10

Related Questions