Is there a way to print long int and int with the same format flag?

I have some code that determines the type of index, so if the user knows that their index space remains in the scope of a normal integer, they can use int

instead long int


    #ifdef LONG_IDX
    typedef long int idx_type
    typedef int idx_type


I have several statements printf

in my code to print out this index data and I don't want to terminate them in statements #ifdef

. Is there a format flag to indicate that the argument can be long int

or int

? If not, is there a way to define a custom format flag that I could just add to my index definition?


source to share

4 answers

You can conditionally define a formatter for your index type:

#ifdef LONG_IDX
typedef long long int idx_type
#define IDX_FORMAT "lld"
typedef int idx_type
#define IDX_FORMAT "d"


Then of course you need to use this in formatting calls, which can get a little cumbersome and (as always!) Require your vigilance and don't forget to do it right when you want to print the index:

idx_type my_index = 47;

print("my_index = %" IDX_FORMAT, my_index);


Note that the above example uses the automatic concatenation of C adjacent string literals to "build" the correct format string at compile time. This is a typical use of this awesome C syntax feature.

Also, if your compiler is good enough for formatting validation (GCC does), you are likely to get useful warnings if you mess up and forget to use a string somewhere defined




I would use %lli

(long long integer) and do the cast when printing:

idx_type idx;

printf("%lli", (long long int) idx);


I think this gives you maximum reliability on what will be printed.



The easiest way is to always include "up".

#include <stdio.h>

int main(void)
    char c = 1;
    int i = 12;
    long int l = 123;
    long long int ll = 1234;

    printf("c=%lld i=%lld l=%lld ll=%lld\n", 
            (long long int) c, 
            (long long int) i, 
            (long long int) l, 
            (long long int) ll
    return 0;




Use either %d

for decimal printing in printf or std::cout




All Articles