Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

gcc

g++

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?

like image 646
Gabi Avatar asked Jul 25 '12 10:07

Gabi


3 Answers

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.

like image 86
Daniel Fischer Avatar answered Nov 13 '22 18:11

Daniel Fischer


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

like image 12
Frédéric Hamidi Avatar answered Nov 13 '22 18:11

Frédéric Hamidi


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

like image 4
Ferruccio Avatar answered Nov 13 '22 18:11

Ferruccio