2

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.

Hank
  • 25
  • 2

2 Answers2

2

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • I guess I didn't stop to think about it. I didn't think that the adding the character would take care of the offset. Thank you again. – Hank Jan 22 '12 at 06:15
  • @Hank: Characters are just integral values, so you can use them arithmetically like any integer. (Note that things like `fgetc` even *want* to return you a more general `int`, even though all you asked for was a `char`.) The reverse can be used to write your own `atoi`: The numeric value of a digit `c` is `c - '0'`... – Kerrek SB Jan 22 '12 at 06:17
0

Characters '0' to '9' are consecutive. The C standard guarantees this.

In ASCII:

  • '0' = 48
  • '1' = 49
  • '2' = 50

etc.

The '0' is simply seen as an offset.

  • '0' + 0 = 48, which is '0'.
  • '0' + 1 = 49, which is '1'.

etc.

Pubby
  • 51,882
  • 13
  • 139
  • 180