Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 282
Swaroop Avatar asked Aug 05 '26 08:08

Swaroop


2 Answers

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

const A &reward = (score > 5) ? foo1() : foo2();
like image 95
Łukasz G. Avatar answered Aug 06 '26 20:08

Łukasz G.


You can use the conditional operator to your advantage. However, you may not use A& reward = ... since both foo1() and foo2() return const A&. You will have to use const A& reward = ....

const A& reward = ( (score > 5) ? foo1() : foo2() );
like image 40
R Sahu Avatar answered Aug 06 '26 22:08

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!