Search code examples
c++ternary-operatorconst-reference

Conditional assignment for const reference objects in C++


Here is a code snippet that illustrates my problem :

class A {...};
const A& foo1() {...}
const A& foo2() {...}

void foo3(int score) {
  if (score > 5)
    const A &reward = foo1();
  else 
    const A &reward = foo2();

  ...

  // The 'reward' object is undefined here as it's scope ends within the respective if and else blocks.

}

How can I access the reward object in foo3() after the if else block? This is required to avoid code duplication.

Thanks in advance !


Solution

  • You may use ternary operator: https://en.wikipedia.org/wiki/%3F%3A

    const A &reward = (score > 5) ? foo1() : foo2();