3
         #include<stdio.h>

         int main()
         {

           char ch = 'A';

           printf("%d\n",'ag');

           printf("%d\n",'a');

           printf("%d, %d, %d, %d", sizeof(ch), sizeof('a'), sizeof('Ag'), sizeof(3.14f));

          return 0;
         }

I used to have many doubts on the output of this question while running on g++ and gcc.

But I have cleared almost all the doubts by referring these links:

  1. Single, double quotes and sizeof('a') in C/C++

  2. Single quotes vs. double quotes in C or C++

I still need to understand one thing about the output of this question.

Can someone please explain the output of printf("%d\n",'ag'); mentioned above in the program. How is it actually stored in the memory?

The output for the program on the Linux/GCC platform is:

24935
97
1, 4, 4, 4
Community
  • 1
  • 1
starkk92
  • 5,754
  • 9
  • 43
  • 59
  • 2
    See http://stackoverflow.com/questions/11737320/how-to-determine-the-result-of-assigning-multi-character-char-constant-to-a-char/11737414#11737414 – hmjd Aug 31 '12 at 09:39

2 Answers2

5

The type of a single-quoted literal is int. So the size is typically large enough for more than one character's worth of bits. The exact way the characters are interpreted is, as far as I know, implementation-dependent.

In your case, you're getting a little-endian ordering:

  • The ASCII value for 'a' is 97 (0x61)
  • The ASCII value for 'g' is 103 (0x67)

Your value is 24935 = 0x6167, so you're getting the 'a' in the higher byte and the 'g' in the lower.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 2
    Confirming the implementation-defined part: ISO/IEC 9899, 6.4.4.4:10: *The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.* – atzz Aug 31 '12 at 09:45
3

What multiple characters mean in single quotes is implementation defined.

6.4.4.4

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. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

For example, in this case 24935 is 0x6167: the ASCII values for the characters a and g side by side.

cnicutar
  • 178,505
  • 25
  • 365
  • 392