Search code examples
cprintftypedef

C: printf with typedef unsigned long long int


I have a typedef that contains a 64bit memory address in hex, but using %x with printf is giving me the following error:

error: format '%x' expects argument of type 'unsigned int', but argument 4 has type 'address'\

This is my declaration of the typedef:

typedef unsigned long long int address;

How can I print this hexadecimal value? Thanks!

Edit: the memory address is not a pointer, I am reading hexadecimal values from another file and need to store these 64bit addresses numerically using the typedef I defined.


Solution

  • The %x conversion specifier expects its corresponding argument to have type unsigned int. To print an unsigned long long, you need to use the length modifier ll, or %llx.

    Handy Table

    Length Modifier        Type
    –––––––––––––––        ––––
                 ll        (unsigned) long long
                  l        (unsigned) long
                  h        (unsigned) short
                 hh        (unsigned) char
                  j        intmax_t, uintmax_t
                  z        size_t
                  t        ptrdiff_t
                  L        long double
    

    So to format an unsigned char value as hex, you’d use %hhx or %hhX. To format a short as decimal, you’d use %hd. To format an unsigned long as octal, you’d use %lo.

    Gratuitous rant

    You’ve just illustrated why I tend to avoid using the typedef facility for primitive types.

    You’ve created what’s known as a leaky abstraction - you’ve ostensibly created a new type to represent an address value, but you have to know that it has been implemented as an unsigned long long in order to use it correctly.

    If you’re going to create an abstract type, you need to go all the way and create abstractions (functions, macros, etc.) for all operations on that type, including input and output (and assignment, and validation, etc.).

    It’s generally not worth the effort for primitive types, so I’d avoid using typedef for this purpose.