0

I have:

  1. string s = "global" [global scope]
  2. 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.
scohe001
  • 15,110
  • 2
  • 31
  • 51
  • 6
    Ask yourself, how `f1` is supposed to see the `s` that's local to `main`. – Lukas-T Jan 07 '20 at 17:03
  • 1
    `f1` doesn't know about the local `s` in `main`, and only sees the global `s`. If you want `f1` to know about main's `s` you'll want to pass it as a parameter. – 1201ProgramAlarm Jan 07 '20 at 17:03
  • 1
    Which book are you using to learn C++? – Lightness Races in Orbit Jan 07 '20 at 17:04
  • See this [question](https://stackoverflow.com/questions/13415321/difference-between-static-auto-global-and-local-variable-in-the-context-of-c-a) for a broader discussion of name scope. – 1201ProgramAlarm Jan 07 '20 at 17:11
  • ```f1()``` should see the local ```s``` because ```std::cout``` sees it too. *e.g.* if I type ```std::cout << s;``` in main, then it will output ```local```. So, the question arises, why doesn't ```f1()``` exhibit the same behaviour? Is it due to the implementation of ```std::cout```? It'd be super useful if somebody sheds some light on this fine point. – Murtaza Magsi Jan 08 '20 at 11:38

1 Answers1

4

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.

gct
  • 14,100
  • 15
  • 68
  • 107