Working Outside of Functions

Is it invalid to define variables and use i/o outside of a function? When I tried compiling this it complains about all lines except the bold declarations: "does not define a type". I have no clue what that means.

1
2
3
4
5
6
7
corporation Corporation1;
Corporation1.wealth = 1000; Corporation1.sharePrice = 1;
person Player1;
Player1.wealth = 1000;
cout << "Choose corporation name: ";
cin >> Corporation1.name;
cout << "Corporation named: " << Corporation1.name;
Last edited on
It means that it doesn't recognize "corporation" or "player" as data types. You may need to include the header defining them?
Each variable has a scope, and they are valid only in their scope.
A local variable is only valid in the scope it was defined, a global variable is valid in all part of the program.
The corporation and person structs were defined directly above that at the root level. The 5 lines moved back into main() compiles:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Begin: Structs
struct corporation {...};
struct person {...};
struct share{...};
// End: Structs
// Begin: Objects
corporation Corporation1;
person Player1;
// End: Objects
void MenuBuySell1 (corporation Corporation) {...}
int main()
{
    ...
    cout << "Choose corporation name: ";
    cin >> Corporation1.name;
    cout << "Corporation named: " << Corporation1.name;
    Corporation1.wealth = 1000; Corporation1.sharePrice = 1;
    Player1.wealth = 1000;
    ...
}


So, I guess there's a rule that operators have to be in functions?
You are not allowed to have free standing code in the space between functions.
That space is for global variable definitions, and declarations and function definitions and such like.



Last edited on
You should show the exact text of error messages.
Topic archived. No new replies allowed.