Is it possible to deduce the format specifier programmatically for a data type? For instance if the print is for a long it automatically does something like:
printf("Vlaue of var is <fmt_spec> ", var);
I also feel it would reduce some errors on part of developer since something like
printf("Name is %s",int_val); //Oops, int_val would be treated as an address
printf("Name is %s, DOB is",name,dob); // missed %d for dob
printf("Name is %s DOB is %d", name);//Missed printing DOB
I understand that the latter two do have warnings but wouldn't it be better if errors were thrown since in most cases it is going to be problematic? Or am I missing something or are there constructs already in place to do so ?
Deduce format specifier from data type?
No.
As melpomene stated:
"Format specifiers aren't just for types. E.g. %o
and %x
both take unsigned int
; %e
, %f
, %g
all take double
; %d
, %i
, %c
all take int
. That's why you can't (in general) deduce them from the arguments."
Point is that if such a functionality existed, then would it deduce unsiged int
to %o
or %x
, for example? And so on . . .
About whether some cases should issue a warning or an issue, you should think about how casting works in c, and when it does make sense to allow something or not. In GCC, you could of course treat warning(s) as error(s):
-Werror
Make all warnings into errors.
-Werror=
Make the specified warning into an error. The specifier for a warning is appended; for example -Werror=switch turns the warnings controlled by -Wswitch into errors. This switch takes a negative form, to be used to negate -Werror for specific warnings; for example -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is in effect.
The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (Printing of the option in the warning message can be disabled using the -fno-diagnostics-show-option flag.)
Note that specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything.
as you can read here.