How do you add a character containing a number char to a number int? What does it mean when '0'+3 is '3'? (3 being an int)

I remember being told once, but never got the hang of it.

Characters are really small integers. '0' is a convenient symbol for the value 48. If you add 1 to 48, you get 49. And 49 is the actual value of the character '1'. Because '0' is a symbol for 48, you can say '0'+1 and still get 49. You can take 49 and print it as an int to get 49, or print it as a char to get '1'. Cool, huh? The decimal digits are required to be contiguous, so you end up with this sequence:

???+1 = '0'
'0'+1 = '1'
'1'+1 = '2'
'2'+1 = '3'
'3'+1 = '4'
'4'+1 = '5'
'5'+1 = '6'
'6'+1 = '7'
'7'+1 = '8'
'8'+1 = '9'
'9'+1 = ???

Be warned! The only characters that have any kind of order specified by C++ are the characters '0'-'9'. If you try to do something like 'a'+1, it is not guaranteed that the result will be 'b'.

Be warned again! ;) For simplicity I used 48 and 49 as examples of the underlying value for '0' and '1', but that is not guaranteed either. The actual value of a character depends on the character set being used. '0' and '1' are 48 and 49 for the ASCII and Unicode character sets, but there are others out there that do not use the same values, like EBCDIC.

Summary: Characters are small integers, you can do arithmetic on them just like on ints and get a different character in the character set. But C++ does not impose restrictions on character sets beyond making the decimal digits have contiguous values. If you rely on any kind of order for other characters, or the actual value of any character, your code may not work the same way everywhere.

Characters are really small integers. '0' is a convenient symbol for the value 48. If you add 1 to 48, you get 49. And 49 is the actual value of the character '1'. Because '0' is a symbol for 48, you can say '0'+1 and still get 49. You can take 49 and print it as an int to get 49, or print it as a char to get '1'. Cool, huh? The decimal digits are required to be contiguous, so you end up with this sequence:

Very cool! I'm amazed at how much I'm learning through a forum. Thank you times a million!

This question has already been answered. Start a new discussion instead.