Lately, I started using lint for static code analysis. One of the warning I get sometimes is regarding this issue. Let's say for instance that I've got the following function:
uint32_t foo( void );
And let's say that I delibertly ignore the return value of the function. To make the warning dissapear, one can write
(void) foo();
My question is, what is the "proper" way to write code like this, should I continue as I always did, since the compiler doesn't complain about it, or should I use the void for clarity, so other code maintainer will know that I delibertly ignored the return value.
When I look at the code like this ( with the void ), it looks pretty strange to me...
It's a warning that stops your compiler from performing it's task (too strict settings). Check the return value of the scanf() function for errors and the warning should disappear.
Many functions return values, but sometimes you don't care what the return value is – you might want to ignore it sometimes, and use it other times. You can use @discardableResult in your own functions. For example, you might write a logging function that accepts a string and optionally also a log level.
scanf() returns a value, and your original code was ignoring (not using) it. Your compiler has an option enabled asking for a warning whenever a result is ignored, so you're getting that warning (not an error, unless you also have something like -Werror)
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.
The common way is to just call foo();
without casting into (void)
.
He who has never ignored printf()
's return value, cast the first stone.
I personally like the "unused" warnings, but on occasion there are instances where I have to ignore them (e.g., the write()
to user, or fscanf(...,"%*s\n")
or strtol()
where the return value is unimportant and I just want the side effect of [maybe] moving the file pointer along.)
With gcc 4.6, it's getting quite tricky.
(void)
no longer works.{ssize_t ignore; ignore=write(...);}
throws up another warning (assigned-not-used).write(...)+1
throws up yet another warning (computed-value-not-used).The only good (if ugly) way to suppress these is to convert the return value into something that the compiler agrees that you can ignore.
E.g., (void)(write(...)+1)
.
This is apparently progress. (And +0
does not work, BTW.)
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