variables defined in main() can be accessed by all functions as well as the main() is still running?

like title described!
Last edited on
Yes.
...But with caveats.

Because snarkiness doesn't actually help the OP. A reasonably useful answer would include the caveats.


You are never allowed to access variables in other functions without some effort. You have to tell the other functions where they are and how to access them.

For example, the following program lets the ask_name() function see and modify the name variable in main(), via an alias (or reference):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

void ask_name( string& answer )
  {
  cout << "What is your name? ";
  getline( cin, answer );
  }

int main()
  {
  string name;
  ask_name( name );
  cout << "Hello, " << name << "!\n";
  }

If main() did not give ask_name() access to the 'name' variable, then ask_name() would not have been able to see or change it.

[edit]
Also, notice how ask_name() doesn't know anything about the actual variable's name. It has it's own alias for it -- answer.
[/edit]

Hope this helps.
Last edited on
Because snarkiness doesn't actually help the OP


Yeah... I need to get better at just ignoring these posts, rather than being a wiseass.
closed account (Dy7SLyTq)
@op: globals can be accessed by all
@duoas: wouldnt it be a reference? i thought alias was when you pass a copy of the object
I admit that such questions could be figured out with a little further study.

Only until recently 'alias' typically meant 'reference'. It depends on context.

In no case can a copy be an alias, since then there would be two objects, not one.
Topic archived. No new replies allowed.