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
}

Recommended Answers

All 2 Replies

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.

A new scope begun with { starts a new scope.

Thanks - I needed that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.