I am reading this book and I have come across this code:
static void
task1(void *args) {
int i;
(void)args;
for (;;) {
gpio_toggle(GPIOC,GPIO13);
for (i = 0; i < 1000000; i++)
__asm__("nop");
}
}
I understand all (relatively) except for line 5. What is (void)args; doing?
args is not used in the function body, and I know that if an argument is not used then one could write
static void
task2(void *args __attribute((unused))) {
// code here
}
which is not being done here. So what is (void) written like that doing?
In general when one does not use an function argument, the compiler is likely to warn you about it. After all if you aren't going to use it why put it there in the first place?
In effect it is an artificial use of the argument that does nothing useful other than telling the compiler you know what you are doing, so "Shatupalready with the warning!"
(void) args works on all of the platforms that I have seen. I believe the __attribute((unused)) is a gcc specific thing.
Every expression has a type. Any expression can be turned into a statement by adding a semicolon. If an expression-statement yields a non-void value, that value is discarded.
Compilers will often warn about a value being discarded. Even a simple case like
printf("hello world\n");
quietly discards the int value returned by printf; a compiler warning might remind the programmer to test that value and take some action if it indicates that the call failed. (Most compilers will not warn in this particular case, since printf calls are usually used in a statement context, with the result ignored.)
Casting an expression to type void discards the result, but it does so explicitly. This is likely to silence a compiler warning.
As far as the language is concerned, a (void) cast converts a result to type void, which is equivalent to discarding that result. From a programmer's point of view, a (void) cast can silence a warning that a value is not used, since you're explicitly ignoring it and asserting to the compiler that you know what you're doing (even if you don't).
Quoting the C standard (N1570 draft), 6.3.2.2:
The (nonexistent) value of a void expression (an expression that has type
void) shall not be used in any way, and implicit or explicit conversions (except tovoid) shall not be applied to such an expression. If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A void expression is evaluated for its side effects.)
and 6.2.5 paragraph 19:
The
voidtype comprises an empty set of values; it is an incomplete object type that cannot be completed.
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