开发者

Query Regarding Character Operations

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.


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.


'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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜