0

Consider a C program:

#include <stdio.h>

int main (void)
{
  int x = 'a';
  printf("%d", x);
}

Here the output is 97 as per the ASCII value table.

But in the example below:

#include <stdio.h>

int main(void)
{
  int x ='aa';
  printf("%d", x);
}

The output is 24929.

Can anyone please explain how the literal has been converted to this integer value?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
smartnerd
  • 85
  • 6
  • 3
    Your second example do not compile correctly: c is not defined, the x initialization is not correct. I think you've got an undefined behaviour. – Mathieu Apr 05 '16 at 08:00
  • 2
    There are no string literals in your code, just character literals. – Spikatrix Apr 05 '16 at 08:02
  • 4
    Note: The value of multicharacter literals is implementation defined. – Spikatrix Apr 05 '16 at 08:03
  • And next time onwards, please post compilable code. I've edited it for you this time. – Spikatrix Apr 05 '16 at 08:06
  • @purplepsycho the second example is *implementation-defined* and it should compile correctly – M.M Apr 05 '16 at 08:11
  • 2
    Those are **not** string literals http://en.cppreference.com/w/c/language/string_literal but rather character literals http://en.cppreference.com/w/c/language/character_constant – CiaPan Apr 05 '16 at 08:15
  • Relace `printf("%d", x);` by `printf("%x", x);` and it will be clearer. – Jabberwocky Apr 05 '16 at 08:20
  • 1
    @MichaelWalz: not really – a better test would be with two *different* characters. – Jongware Apr 05 '16 at 08:26

2 Answers2

3

int x ='aa';

This is valid but value of x is implementation defined. And btw, this is not a string literal. String literal would be this "aa".

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
0

You assigned a value to the int using octets : 'a' is 0x61.

So writing int x = 'aa' is like writing int x = 0x6161.

Edit: but do not write that. Just write int x = 0x6161 or int x = 24929.

Boiethios
  • 38,438
  • 19
  • 134
  • 183