Home > OS >  Is there any benefit at all for explicitly discarding a value via (void) in C
Is there any benefit at all for explicitly discarding a value via (void) in C

Time:02-24

One of the uses of the void keyword in C/C is to discard the value of an expression:

(void) expr;

Is there any benefit at all of the above construct except to avoid "unused parameter" warnings like the below?

void foo(int x, int y) {
  (void) x;
  //..
}

CodePudding user response:

C

Because void is not a reference to object type, the result of this cast is a prvalue even if the input was an lvalue. In C this is stated in [expr.cast].

Based on that fact, it should force an lvalue-to-rvalue conversion on the expression. For ordinary variables, such a conversion with discarded result has no side effects and can and will be removed by the optimizer, however for volatile lvalues, that conversion is a volatile side-effect and cannot be discarded.

However, there's a detail in [expr.static_cast] that throws a fly into the ointment:

Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression ([expr.prop]).

Thus the result prvalue didn't come from converting the expression, it is simply a void prvalue created out of thin air. The expression still isn't forced to undergo lvalue-to-rvalue conversion (but it might, according to the rules of discarded-value expressions).

So in the end there is no effect at all from a cast to void, except possibly changing your compiler's warning heuristics.

  •  Tags:  
  • c c
  • Related