Home > Software engineering >  Is it safe to print an unsigned char with the %u specifier via the printf function?
Is it safe to print an unsigned char with the %u specifier via the printf function?

Time:12-17

So, I realize that %u is for printing an unsigned int. And unsigned int is usually more than a single byte (typically 32 bits/4 bytes I think) on most systems. unsigned char is always one byte. So, is it safe to use the %u format specifier to print a byte as a number? Will type promotion kick in? Or does the variadic argument list muck things up? Here's a simple example:

#include <stdio.h>

int main()
{
    unsigned char val = 'A';
    printf("%u", val);  // is this safe?
}

Assuming an ASCII encoding, the output should be 65. However, as %u is technically for unsigned int rather than unsigned char, I'm curious if there are there cases where I would get bytes of garbage, or access the stack in an unexpected way.

CodePudding user response:

%u expects an unsigned int, so you will have to cast the unsigned char when passing it to %u, eg:

printf( "%u", (unsigned int) val );

It is likely that when passing the unsigned char as-is, it gets promoted to the size of the unsigned int when pushed onto the call stack, in which case %u may work without casting, but you should not rely on that behavior. Jut pass the correct type to begin with.

Alternatively, you can use %hhu instead (C99 ), which expects an unsigned char, eg:

printf( "%hhu", val );
  • Related