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,084
  • 3
  • 11
  • 24

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
  • 50,629
  • 12
  • 125
  • 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,642
  • 5
  • 24
  • 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
  • 20,895
  • 3
  • 42
  • 52
  • 2
    `int` doesn't have to be four bytes. – chris Apr 12 '13 at 04:14
  • Thank You I asked the question based on the last quote mentioned by you. C++ is superset of C – Kranthi Kumar Apr 12 '13 at 04:26
  • @Kranthi It most certainly is not a strict superset. Related: ["C subset of C++" -> Where not ? examples?](http://stackoverflow.com/q/1201593), [What prevents C++ from being a strict superset of C?](http://stackoverflow.com/q/3777031) – Cody Gray Apr 12 '13 at 04:27
  • Why does sizeof (3.14) takes 8 bytes. 3.14 is float right – Kranthi Kumar Apr 12 '13 at 04:30
  • 1
    @Kranthi Kumar In Java, C and C++, `3.14` and `3d` are a double literal while `3.14f` is a float literal – Patashu Apr 12 '13 at 04:32