9

I have written a small printf statement which is working different in C and C++:

    int i;
    printf ("%d %d %d %d %d \n", sizeof(i), sizeof('A'), sizeof(sizeof('A')),    sizeof(float), sizeof(3.14));

The output for the above program in c using gcc compiler is 4 4 8 4 8

The output for the above program in c++ using g++ compiler is 4 1 8 4 8

I expected 4 1 4 4 8 in c. But the result is not so.

The third parameter in the printf sizeof(sizeof('A')) is giving 8

Can anyone give me the reasoning for this

Kranthi Kumar
  • 1,184
  • 3
  • 13
  • 26

3 Answers3

14

It's nothing to do with the sizeof operator in particular; rather, the size of character literals in C is different than C++, because character literals in C are of type int, whereas in C++ they are of type char.

See Why are C character literals ints instead of chars? for more information.

Community
  • 1
  • 1
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
3

Yes, it is implementation specific. sizeof() returns size_t which is unsigned integer. Its size is dependent on machine(32-bit vs 64-bit) and also implementation.

Nishanth
  • 6,932
  • 5
  • 26
  • 38
2

As explained in Size of character ('a') in C/C++ :

In C, char is one byte, but 'a' is an int constant so it is (in your case, depending on what architecture you compile on!) four bytes wide. in C++, both char and 'a' are char with one byte size.

The most important message is that C++ is not a superset of C. It has a lot of small breaking changes like this.

Community
  • 1
  • 1
Patashu
  • 21,443
  • 3
  • 45
  • 53