I have the following code in C:
(void)fscanf(fp, "%*d %*d %d %d %d\n",&z, &e, &a);
I cast the call to void as the return value of fscanf is irrelevant for me. But I get the following warning when compiling:
warning: ignoring return value of ‘fscanf’, declared with attribute warn_unused_result [-Wunused-result]
(void)fscanf(fp, "%*d %*d %d %d %d\n",&z, &e, &a);
Shouldn't the '(void)' have taken that warning out?
That's a nice warning, since ignoring the return value of fscanf()
could lead to undefined behavior. I suppose you can't silence that warning unless you handle the return value, that's very easy
if (fscanf(fp, "%*d%*d%d%d%d", &z, &e, &a) == 3)
usevalues(z, e, a);
else
reportproblem_do_not_use_z_e_or_a();
Warnings are good teachers of how to correctly use functions, you should never ignore fscanf()
's return value, and more importantly you should never ignore/silence a warning. If the compiler is warning about something, it must be because you are doing something wrong1.
In this case, if you don't check the value and proceed to use z
, e
or a
their content might be undefined at the moment of reading them and some unexpected things will occur.
The worst part is that it will be very difficult to find out that, these unexpected things (calculations for example) are happening because you DID NOT CHECK fscanf()
's return value.
1Except in very few situations, where you intentionally do something that will trigger a warning. But those kinds of situations only happen when you are a very experienced c programmer.
This is the defined behavior for this attribute. When a function is marked with this attribute, the return value cannot be ignored by casting it to void.
See this bug report 25009 for an interesting discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With