I have:
string s = "global"
[global scope]string s = "local"
[local scope (main function)]I want function f1()
to print out the local s
when it is called from main
, but the function is printing the global s
instead.
#include <iostream>
using namespace std;
//global variables & functions .h
string s = "global"; void f1();
//main begins
int main()
{
string s = "local";
f1();
return 0;
}
//function definitions .cpp
void f1()
{
cout << s;
}
Output is:
global
Process returned 0 (0x0) execution time : 0.281 s
Press any key to continue.
That's because the global definition is the only one visible to f1
. This is the difference between lexical and dynamic scoping, which I recommend you look up the definitions of. C++ is lexically scoped, which means it can only see symbols based on where they're defined relative to the code. f1
can only see local variables defined inside it, and globals, it doesn't even know the variable in main
exists.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments