Why is this program's output different between C and C++?

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

The following program

#include <stdio.h>

int main()
{
    printf("%dn", sizeof(''));
    printf("%dn", 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?


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 .


The 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++).


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

链接地址: http://www.djcxy.com/p/85772.html

上一篇: 4.2 Mac OSX Mountain Lion出现错误,无法安装mysql

下一篇: 为什么这个程序的输出在C和C ++之间是不同的?