Search code examples
c++syntaxvoid

What is calling void(); doing?


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.


Solution

  • 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.