I am trying to understand why the following statement works:
putchar( 1 + '0' );
It seems that the + '0' expression converts the literal to the respective ASCII version (49 in this particular case) that putchar likes to be given.
My question was why does it do this? Any help is appreciated. I also apologize if I have made any incorrect assumptions.
This has nothing to do with ASCII. Nobody even mentioned ASCII.
What this code does assume is that in the system's character encoding all the numerals appear as a contiguous range from
'0'
to'9'
, and so if you add an offset to the character'0'
, you get the character for the corresponding numeral.All character encodings that could possibly be used by a C or a C++ compiler must have this property (e.g. 2.3/3 in C++), so this code is portable.