Home > database >  Printing int using putchar() in C
Printing int using putchar() in C

Time:09-16

I have just discovered that to print an integer using the putchar() function, I need to add '0'. What is the importance of this '0'?

CodePudding user response:

The argument to putchar is the ASCII code* of the char you want to print. The digits 0 thru 9 are encoded as the consecutive numbers 48 thru 57. So, to print the one-digit number n, you can write:

putchar(48   n);

Without the addition of the constant 48, you wouldn't get digit; you'd get a control character such as Backspace (8) or Tab (9).

But it's preferable to write

putchar('0'   n);

Because in C, a single-quoted character literal has a numeric value equal to its ASCII code, so '0' is just another way to write 48, but has the advantage of not requiring you (or a future maintenance developer) to memorize the ASCII chart to know that '0' == 48.


(*Technically, the C standard doesn't assume an ASCII-compatible character set, and C compilers exist for EBCDIC systems. But that's probably not relevant to a beginner.)

CodePudding user response:

Perhaps this bit of code and its output will help clarify...

int main() {
    for( int i = 0; i <= 9; i   ) {
        printf( "%d (binary) transformed to printable ASCII ", i );
        putchar( '0'   i );
        putchar( '\n' );
    }

    for( char c = '0'; c <= '9'; c   ) {
        putchar( c );
        printf( " (X hex) printable ASCII char for binary %d\n", c, c - '0' );
    }

    printf( "'Count' up the (uppercase) ASCII alphabet\n" );
    for( int l = 0; l < 26; l   )
        putchar( 'A'   l );
    putchar( '\n' );

    return 0;
}

Abridged Output

0 (binary) transformed to printable ASCII 0
1 (binary) transformed to printable ASCII 1
2 (binary) transformed to printable ASCII 2
...
8 (binary) transformed to printable ASCII 8
9 (binary) transformed to printable ASCII 9
0 (30 hex) printable ASCII char for binary 0
1 (31 hex) printable ASCII char for binary 1
2 (32 hex) printable ASCII char for binary 2
...
8 (38 hex) printable ASCII char for binary 8
9 (39 hex) printable ASCII char for binary 9
'Count' up the (uppercase) ASCII alphabet
ABCDEFGHIJKLMNOPQRSTUVWXYZ
  •  Tags:  
  • c
  • Related