I have a code which defines an index type so that if a user knows that their index space remains in the realm of a normal integer they can use int instead of long int.
#ifdef LONG_IDX
typedef long int idx_type
#else
typedef int idx_type
#endif
I have some printf statements in my code to print out this index data and I don’t want to wrap them in #ifdef statements all over the place. Is there a format flag to specify that the argument may be a long int or an int? If not, is there a way to define a custom format flag that I could simply add to my index type definition?
You can conditionally define a formatter for your index type:
Then you of course need to use this in the formatting calls, which can become a bit cumbersome and (as always!) requires you to be vigilant and remember to do it right when you want to print an index:
Note how the above uses C’s automatic concatenation of adjacent string literals to “build” the proper formatting string at compile-time. This is a typical usage of that awesome feature of C’s syntax.
Also, if your compiler is nice enough to do formatting string validation (GCC does), you will very likely get helpful warnings if you do mess up and forget to use the
definedstring somewhere.