I'm trying to declare a variable in an if-else block as follows:
int main(int argc, char *argv[]) {
if (argv[3] == string("simple")) {
Player & player = *get_Simple();
} else if (argv[3] == string("counting")) {
Player & player = *get_Counting();
} else if (argv[3] == string("competitor")) {
Player & player = *get_Competitor();
}
// More code
}
But, I'm getting the following errors when I try to compile:
driver.cpp:38: error: unused variable ‘player’
driver.cpp:40: error: unused variable ‘player’
driver.cpp:42: error: unused variable ‘player’
driver.cpp:45: error: ‘player’ was not declared in this scope
Any ideas?
Your problem is that player falls out of scope in each if / else if block.
You need to declare your variable above all of the if statements.
But you can't use a reference for that because you must initialize a reference right away.
Instead you probably want something like this:
int main(int argc, char *argv[]) {
Player * pPlayer = NULL;
if (argv[3] == string("simple")) {
pPlayer = get_Simple();
} else if (argv[3] == string("counting")) {
pPlayer = get_Counting();
} else if (argv[3] == string("competitor")) {
pPlayer = get_Competitor();
}
//Then if you really want to...
Player &player = *pPlayer;
}
Others have suggested pointers. However, the conditional operator may be used as well.
Player & player = argv[3] == string("simple") ? get_Simple()
: argv[3] == string("counting") ? get_Counting()
: get_Competitor();
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