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 !
You may use ternary operator: https://en.wikipedia.org/wiki/%3F%3A
const A &reward = (score > 5) ? foo1() : foo2();
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() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With