-4
char c; 
c = '2';
printf("%d\n",c);

So this question is from my quiz, it is asking what is the display. The answer is 50, i tried by using program, but why it is 50? not 2 or anything?

  • 1
    It seems your system (like most systems today) is using [the ASCII character set](http://www.ascii-code.com/). If you check the link, you might understand why `'2' == 50`. – Some programmer dude Oct 06 '14 at 13:53
  • 2
    Also, please try to come up with better titles for your questions in the future. The question has nothing to do with apostrophes. – Some programmer dude Oct 06 '14 at 13:55

2 Answers2

4

The apostrophes mean "character literal", i.e. '2' is not the integer 2, but instead the character 2, i.e. the glyph used to represent the single digit 2.

You print this value using %d in printf(), which means "signed integer", so you get the integer value of the character, often called the "code point" (or, classically, it's "ASCII value").

I think your code is not 100% clean, since char might be unsigned, you should cast to (int) in the call to be clear, since int is what %d expects.

unwind
  • 391,730
  • 64
  • 469
  • 606
3

You are printing a char '2', as an int '%d', so what gets printed, is its ASCII value

nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
A4L
  • 17,353
  • 6
  • 49
  • 70