0

If I uncomment the 'int x;' above main, and comment out the int x = 0 inside of main, it works, but I don't want to use global variables.

What I can't understand is why x is out of scope. The text I'm using says “vars having local or block scope may be used only in the part of the program between their definition and the block’s closing brace” - so if I declare x at the start of the main function, it seems like its scope should last until the end of the whole program, and x should be usable in all functions that follow its initialization.

#include <iostream>
using namespace std;

void nonRefVarChanger();
//int x;

int main () 
{
    int x = 0;
    nonRefVarChanger();
    cout	<< "x is "	<< x	  << endl;
    return 0;
}
// Fn def
void nonRefVarChanger() // also wanted to avoid passing by reference
{
	x = 5; // error: 'x' was not declared in this scope
}
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by richman0829
0

What I can't understand is why x is out of scope. The text I'm using says “vars having local or block scope may be used only in the part of the program between their definition and the block’s closing brace” - so if I declare x at the start of the main function, it seems like its scope should last until the end of the whole program, and x should be usable in all functions that follow its initialization.

No. If you have scope from { to }, note that main has these. A new scope begun with { starts a new scope.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.