Hank
Hank

Reputation: 25

Converting Decimal Literals to ASCII Equivalent for putchar in C

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.

Upvotes: 2

Views: 928

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

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.

Upvotes: 2

Pubby
Pubby

Reputation: 53037

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.

Upvotes: 0

Related Questions