21

Possible Duplicate:
Size of character ('a') in C/C++

The following program

#include <stdio.h>

int main()
{
    printf("%d\n", sizeof('\0'));
    printf("%d\n", sizeof(0));
}

compiled with gcc outputs

4
4

and with g++

1
4

Why is this happening? I know this it's not a compiler thing but a difference between C and C++ but what's the reason?

Community
  • 1
  • 1
Gabi
  • 600
  • 2
  • 13

4 Answers4

35

In C, character constants have type int per 6.4.4.4(10) of the standard,

An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer.

Thus you're printing out the size of an int twice.

In C++, character constants have type char.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
12

The \0 character literal is treated as an int in C, so you actually end up printing sizeof(int) instead of sizeof(char).

ideone gives the same results (C, C++).

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 1
    @Konrad, true, everything smaller than an `int` is considered as an `int` in C. Fixed. – Frédéric Hamidi Jul 25 '12 at 10:09
  • No, that’s also not true, not *everything* is treated as `int`, only character literals: http://ideone.com/ZQIPC – Konrad Rudolph Jul 25 '12 at 10:12
  • @Konrad, the `short` test in your example uses a cast. Of course, there is no way to express a `short` literal, so even a value fitting in a `short` is parsed as an `int` from the get-go. Indeed, it would be interesting to know if a would-be `short` literal would be treated the same way as a `char` one... – Frédéric Hamidi Jul 25 '12 at 10:18
  • But your comment doesn’t talk about literals, it talks about *values*. And since C simply doesn’t have integer literals for anything other than `int`, the comment wouldn’t make sense if it talked about literals (rather than values) anyway. – Konrad Rudolph Jul 25 '12 at 10:24
  • @Konrad, ah, I was actually talking about literals (`int` and `char` ones, since `short` literals do not actually exist), not values. I agree my comment is ambiguous, though, I probably should have found a better way to express that. – Frédéric Hamidi Jul 25 '12 at 10:30
4

In C character literals are ints. In C++ they are chars.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
0

The output is already compiler dependent since you use the wrong format specifier for size_t this would be %zu. On 64 bit systems with size_t wider than int this could give you any sort of garbage.

Otherwise this shure is compiler dependent. Both values that you try to print the size of are int in C and char and int in C++. So in C this should usually give you 4 4 or 8 8 and in in C++ 1 4 or 1 8.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177