Nicely formatting number types

I came across the following compiler warning today:

||   CC     libplurk_la-plurk-item-view.lo
|| plurk-item-view.c: In function ‘construct_image_url’:
plurk-item-view.c|233| warning: format ‘%lld’ expects type ‘long long int’,
but argument 3 has type ‘gint64’

Tut tut tut .. a compiler warning! How could the commiter had let this happen? Lets look at the code …

url = g_strdup_printf ("http://avatars.plurk.com/%s-medium%lld.gif", ...);

Ahaha .. they’re probably using a 32-bit system, the nice thing to do here is:

url = g_strdup_printf ("http://avatars.plurk.com/%s-medium%" G_GINT64_FORMAT ".gif", ...);

To handle the case that on a 64-bit system you can represent a gint64 as a long rather than needing to go for a long long. I’ve seen this quite a bit with debugging output for size_t for which G_GSIZE_FORMAT is definitely your friend.

2 thoughts on “Nicely formatting number types

  1. MadCoder

    Or you can use:

    %d for int/int32
    %ld for long
    %lld for long long
    %zd for size_t
    %jd for int64_t

    Of course those won’t work when uint128_t will begin to exist since %jd will then be for uint128_t but as of now, there isn’t a single architecture with 128 bits integers so you’re pretty safe whith those.

    Also there is in C PRI[diouxX]* in which are way shorter than the glib (ugly) equivalents.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>