# Char and switch output

• 07-09-2012
Confuzero
Char and switch output
Hi, could anybody explain to me why the code below outputs "5050"? I'm having huuuge problems understanding the whole deal with char. I just don't get it at all.

The way I see it, "c = '1' + 1;" means c is currently 1, but not the ASCII code, but the actual character 1, because of ' '. Then you add 1 to it, which now makes it character 2.

After that it's a blank. How does it suddenly become 5050?

Thanx!

Code:

```#include <stdio.h> int main() {     char c;     c = '1' + 1;     switch (c) {     case '1': printf ("%d", c);     case '2': printf ("%d", c);     case '3': printf ("%d", c);break;     default: printf ("default");     }     return 0; }```
• 07-09-2012
grumpy
In the ASCII character set, '1' has the numerical value of 49, and '2' has the numerical value of 50. %d prints the numerical value (which is what you are seeing). %c will print the character '2'.

If you do a test, you will find that ('1' == 49) will yield true (again, assuming compatibility with the ASCII character set).

You might want to look at this link. Note that the value '0' has decimal value 48 in the ASCII character set, and other digits have values that follow from there sequentially.

'2' + 1 should be the value '3' (51 in ASCII). If you are not getting that, you are doing something wrong. '2' + '1', however, will have the value 99, which corresponds to the letter 'c' in ASCII (and something else, if your compiler or host system work with a different character set).
• 07-09-2012
Confuzero
Thanx for the answer, grumpy, I think I get it, but let me review, just to be sure.

"c = '1' + 1;" means you add 1 to the character '1' so it becomes '2', and numerical value of '2' --> 50

Then, because "c = '1' + 1;" equals 2, case 2 and case 3 get executed, they output the numerical value of the character '2' because of %d --> 5050

and at the end of the case 3 is a break, so the switch ends. Is that it?
• 07-09-2012
std10093
Yes,case 2 and case 3 will be executed ;) If you remove break default will also be shown at your screen :)
• 07-09-2012
Confuzero
Great! Thanx to both of you.