I came across void();
being used as a 'do-nothing' in the 'else' branch of a ternary operator, as a shorthand for a null pointer check
if(var){ var->member(); }
as
var ? var->member() : void();
but I can't seem to find any reference to the void
keyword being used in this way, is this a function or functor call on the void
keyword itself? or is it casting nothing to the type of void
? or is this just the c++ syntax of something like pass
?
Edit:
The return type of member()
is void
in this situation.
You are just "constructing" a prvalue (not a variable, for the reason suggested in the comments) of type void
, just as int()
would default-construct an int
.
As others said in the comments, the second alternative is pejorative. The ternary operator is, well, ternary because it has the if
, the then
, and the else
parts. If you don't need an else
, why would you write one and leave it empty?
That alternative is even uglier and more cryptic than this,
if(var){
var->member();
} else {}
which may just look stupid.
Assuming var->member()
has type void
,
var ? var->member() : void();
has type void
and either evaluates var->member()
or evaluates void()
if var
is null.
Now, void()
is an expression; according to [expr.type.conv]/2
, it just does nothing:
if the type is cv
void
and the initializer is()
or{}
(after pack expansion, if any), the expression is a prvalue of the specified type that performs no initialization.
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