質問

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top