seamus
seamus

Reputation: 2901

Why does %c print '?' and what is its meaning

Two examples

printf("\n %c , ((unsigned char)a[i]+100);

printf("\n %c , -11);

Returns

?
?

Upvotes: 0

Views: 1480

Answers (4)

chux
chux

Reputation: 154255

"%c" expects an int.

(unsigned char)a[i]+100 is a (unsigned char) + (int). When (unsigned char) is 8-bit (most common), this results in an int. Thus, in both of the below, code pass an int to printf().

printf("\n %c , ((unsigned char)a[i]+100);
printf("\n %c , -11);

"%c" converts that int to a unsigned char.

c ... the int argument is converted to an unsigned char, and the resulting character is written. C11dr §7.21.6.1 8

Assuming an 8-bit unsigned char, that converted value is in the range 0 to 255. -11 becomes 245. Then the character is written. For values in the ASCII range of 0-127, we usually see the ASCII character or effect of a control character. Other values print other things.

Certainly on OP's platform the output defaults to ? for many of those out-of-ASCII-range characters. @paddy

Upvotes: 1

malanb5
malanb5

Reputation: 314

You are missing a closing " in both statements. What compiler are you using? If you compile with gcc with the -Wall compiler flag on you would see:

warning: missing terminating " character
     printf("\n %c , ((unsigned char)a[i]+100);

Upvotes: 2

tadman
tadman

Reputation: 211680

Character -11 is not a valid 7-bit ASCII character. It's also an invalid UTF-8 byte, hence the ? result.

Only characters 0-127 are valid for %c. Everything else is going to be part of a multi-byte UTF-8 character, or is character-set dependent.

Upvotes: 2

user2589273
user2589273

Reputation: 2467

You guessed it, c returns a character. This means that in %c a character is substituted at that location within the print string.

Upvotes: 0

Related Questions