Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing data type char with printf()

Tags:

c

format

printf

The printf() function uses the format specifier %s to print char *. The standard does not specify how char is implemented as signed or unsigned.

So when char is implemented as signed char, and we use %s to print unsigned char *, is it safe to do this?

Which format specifier should we use in this case?

like image 219
user8174916 Avatar asked Mar 08 '23 23:03

user8174916


1 Answers

... when char is implemented in signed char, and we use "%s" to print unsigned char*. Is it safe to do this?

Yes it is safe.

char *cp = ...;
signed char *scp = ...;
unsigned char *ucp = ...;
printf("%s", cp);  // OK.
printf("%s", scp);  // OK.
printf("%s", ucp);  // OK.

(%s) ... the argument shall be a pointer to the initial element of an array of character type. ... C11dr §7.21.6.1 8

The three types char, signed char, and unsigned char are collectively called the character types. C11 §6.2.5 15

like image 113
chux - Reinstate Monica Avatar answered Mar 24 '23 19:03

chux - Reinstate Monica