B
BartC
Ben Bacarisse said:I think you proposal is just a little off. You need, in my opinion,
%?d. The compiler can then determine the right length modifier, but
surely you know you want a signed decimal conversion? %?x does hex
conversion for an unsigned type of whatever length. For example, when
the argument is a size_t, %?x would generate %ux. You could, as final
touch, allow %?? which would fill in the length *and* decide on one of
'd', 'u' or 'g' for the conversion specifier based on the type.
Yes, %?? would tick all the boxes (apart from not being able to use just %?
in the majority of cases).
In general, you might have a variable with a typedef-ed type like this:
T a;
where the only thing you know about T is that it's numeric (and might
further know that it's an integer type). And want to quickly print the value
of it:
printf("A = % ....\n", a);
In this case, you don't necessarily know if a is signed or not. You can find
out, but the idea is to avoid going to that effort. And also if T changes,
or this code fragment gets pasted elsewhere where T might be different, then
you want to avoid having to update all these format specifiers.
Actually the same applies even when T isn't a typedef; one day it might just
change from int to long long int; at ordinary warning levels, you will not
be aware anything is amiss.
Of course in the case of the format string not being a constant, then you
can't really use this, unless somehow the compiler can impart type
information to the printf handler, but that would be a bigger, more
disruptive change to how printf works.
(My point of view is from writing this stuff outside of C where you might
just do 'println a'; in general you don't need to specify anything at all,
unless you want extra control over the formatting, but even then you don't
normally need to say what the type of the variable is - the compiler knows
that already, and better than you!)