nalzok
nalzok

Reputation: 16107

Is printing negative numbers as characters well-defined in C?

For example, the following code:

#include <stdio.h>
#include <limits.h>

int main(void)
{
    char a;
    signed char b;
    for(a = CHAR_MIN, b = CHAR_MIN; a < CHAR_MAX ; a++, b++ )
    printf("%c %c\n", a, b);
}

outputs:

! !
" "
# #
$ $
% %
& &
' '
( (
……

When a and b are negative, characters are still printed on the screen. I wonder whether this behaviour is well-defined?

If so, is it defined by the standard or an specific implementation? And what's the point of defining such behaviour?

Upvotes: 1

Views: 1929

Answers (2)

chux
chux

Reputation: 153348

Yes

When a value is passed to match "%c" is it converted to an int or unsigned as part of the usual integer promotions due to the ... of the printf() arguments.

When printf() see that int value, it converts to to an unsigned char. Then the corresponding character is printed.

c If no l length modifier is present, the int argument is converted to an unsigned char, and the resulting character is written. C11dr §7.21.6.1 8

So passing any narrow type integer that is promoted to int or even an unsigned within the range of INT_MAX is not a problem.

Upvotes: 4

YOHAN
YOHAN

Reputation: 29

200 is 11001000 (in binary number), so -200 is 100111000 by one's complement.

The size of 'char' is just 8 bits, and -200 is 00111000 (= 56 in decimal number).

ASCII code of 56 is '8', and that's why you can see '8' as your output.

If you print out it as '%d', you can see '56' as an output.

Upvotes: 0

Related Questions