tags:

views:

50

answers:

3

Hi,

Please explain the following piece of code..

   printf("%c\n",0+'0'); --> returns 0
   printf("%c\n",1+'0'); --> returns 1
   printf("%c\n",0+'1'); --> returns 1
   printf("%c\n",1+'1'); --> returns 2

Thanx.

+3  A: 

Look at the ASCII table. '0' has code 48. So '0' + 1 yields 49, which is '1'. So every character is in fact an integer. You add another integer to it and then, because you specify "%c" in printf, you force it to consider it a character. He goes check his ASCII table and, after some deliberation he decides to print the output to the screen.

nc3b
Thanks.. Is this the correct way to accept the answer?? by ticking onto the question.. I am doing it all the time now for every question i ask, but it still not increasing my accept rate??
AGeek
@RBA: It takes a moment to recalculate the accept rate. :-)
Aaron Digulla
+1  A: 

'0' gives the ASCII value of char 0 which is 48. To that you add 0 to get 48. Then you print 48 back as a character which gives 0

Similarly the next one adds 1 to 48 to give 49 which when printed as char gives 1

codaddict
+1  A: 

Thanks to %c all of them print the character equivalent of the argument.

printf("%c\n",0+'0');

Adds zero to the ASCII value of the character zero which is 48: 48 + 0 = 48.
Try printf("%d\n", '0'); to get the ASCII value.

printf("%c\n",1+'0'); // 1 + 48 = 49 which is the character `1`
printf("%c\n",0+'1'); // 0 + 49 which is again `1`
printf("%c\n",1+'1'); //left as an exercise
Amarghosh
Thanks.. this one was correct too :-)
AGeek
@RBA Just as an FYI, normally in SO you thank a person by up-voting his answer - by pressing the up-arrow towards the left side of the answer. This will give him/her 10 reputation points. (I've made this answer CW so that I won't earn any rep on this answer; didn't wanna sound begging for rep - just wanted to let you know the custom)
Amarghosh