Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is calling void(); doing? [duplicate]

Tags:

c++

syntax

void

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.

like image 807
Jay Avatar asked Apr 11 '20 21:04

Jay


2 Answers

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.

like image 176
Enlico Avatar answered Oct 14 '22 06:10

Enlico


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.

like image 8
YSC Avatar answered Oct 14 '22 07:10

YSC