3

I'm trying to find out whether the following code is valid (even if dubious in appearence)?

void hello(int, int) {}

int main() {
    int a = 1;
    int b = 2;
    
    a == b
        ? hello(a, b) 
        : void();

    return 0;
}

I have not found anything suggesting this would be invalid, and it compiles fine on clang and gcc. Questions I could find on SO were about void() in the context of decltype here and sizeof here. It seems to mean different things in different contexts. If it is valid, I would like to know:

  • What exactly does void() evaluate, if it does that at all, to? Can it be treated the same as an effectless void function call? Just void, in this use case, gives me a compiler error.
  • Why is it not possible to simply omit one side of the ternary conditional?
Kotz
  • 89
  • 1
  • 8

2 Answers2

3

void() is a valid expression which yields a prvalue of type void. It can therefore be used as a branch in the conditional operator.

The language does not allow you to omit one branch of the ternary conditional operator but if, for whatever reason, an if block is not to your liking, you could write

a == b && (hello(a, b), true);

where hello(a, b) will only be evaluated if a equals b.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

What exactly does void() evaluate, if it does that at all, to?

Here, void() is in a context where the grammar expects an expression rather than a type. As such, it has the same meaning as in the linked question What does the void() in decltype(void()) mean exactly? i.e. it is a prvalue expression of type void.

Why is it not possible to simply omit one side of the ternary conditional?

The grammar of the language does not allow that.

eerorika
  • 232,697
  • 12
  • 197
  • 326