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: