scope of if statements

For practice I'm trying to make a program that chooses a U.S. president at random, presents the name to the user, and then lets the user input a number corresponding to the order of their term. (Hoping to add more things, such as year of term, etc. later)

The problem is that I'm using an if statement to select the president, and it causes the initialization of my pointer to be out of scope when I return to main.

For right now I'm only using two presidents until I can get the idea.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>

using namespace std;


int main()
{
    struct President {
    string name;
    int place;
    };

    President GW;
    President JA;

    GW.name = "George Washington";
    GW.place = 1;

    JA.name = "John Addams";
    JA.place = 2;

    President *apresident = NULL;

    srand (time(NULL));
    int selector = (rand() % 2 + 1);

    if (selector == 1) {
    President *apresident = &GW;
    }

    if (selector == 2) {
    President *apresident = &JA;
    }

    cout << apresident->name;

    return 1;
}


"cout << apresident->name;" inside of the if statements work, but outside of the if apresident is undefined. I would like a way to do the selection so that it is understood outside of the ifs.

I was thinking of trying to use a function to do it, but I couldn't use a structure as a parameter, so I couldn't pass it. Any help would be appreciated.
Your declarations of apresident within the if statements are hiding the declaration of apresident in main. You need to simply assign apresident in the if statement as opposed to redeclaring it:

1
2
3
4
5
6
7
if (selector == 1) {
President * apresident = &GW;
}

if (selector == 2) {
President * apresident = &JA;
}


but I couldn't use a structure as a parameter

You can use a structure as a parameter but you wouldn't be able to use President as a parameter if it's declared in main. Moving the declaration out of main will do the trick.

1
2
3
4
5
6
7
8
9
10
11
12
13
struct President {
string name;
int place;
};

void functionThatTakesAPresident(const President& prez)
{
}

int main()
{
   ...
}
Thank you so much, that did the trick!
Topic archived. No new replies allowed.