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
#else
typedef int idx_type
#endif
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
You can conditionally define a formatter for your index type:
#ifdef LONG_IDX
typedef long long int idx_type
#define IDX_FORMAT "lld"
#else
typedef int idx_type
#define IDX_FORMAT "d"
#endif
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
.
source to share