Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable in an if-else block in C++

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?

like image 455
Ian Burris Avatar asked Nov 24 '09 23:11

Ian Burris


2 Answers

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;

}
like image 100
Brian R. Bondy Avatar answered Sep 28 '22 14:09

Brian R. Bondy


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(); 
like image 34
rlbond Avatar answered Sep 28 '22 13:09

rlbond