scope - Global and local variables in C++ -
i'm new c++, , i'm experiencing issues when printing local , global variables. consider simple piece of code:
#include <cstdlib> #include <iostream> using namespace std; /* * */ int x = 10; // x global int main() { int n; { // pair of braces introduces scope int m = 10; // variable m accessible within scope cout << m << "\n"; int x = 25; // local variable x hides global x int y = ::x; // y = 10, ::x refers global variable x cout << "global: " << y << "\n" << "local: " << x << "\n"; { int z = x; // z = 25; x taken previous scope int x = 28; // hides local variable x = 25 above int t = ::x; // t = 10, ::x refers global variable x cout << "(in scope, before assignment) t = " << t << "\n"; t = x; // t = 38, treated local variableout not declared in scope cout << "this hidden scope! \n"; cout << "z = " << z << "\n"; cout << "x = " << x << "\n"; cout << "(in scope, after re assignment) t = " << t << "\n"; } int z = x; // z = 25, has same scope y cout << "same scope of y. @ code! z = " << z; } //i = m; // gives error, since m accessible within scope int m = 20; // ok, since defines new variable m cout << m; return 0; } my goal practicing accessibility of variables within various scopes, , printing them. however, i'm not able figure out why when try print last variable z, netbeans gives me output 2025. here follows sample output:
10 global: 10 local: 25 (in scope, before assignment) t = 10 hidden scope! z = 25 x = 28 (in scope, after re assignment) t = 28 same scope of y. @ code! z = 2520 run finished; exit value 0; real time: 0ms; user: 0ms; system: 0ms hope can me understanding going on! :)
is not z holding value 2520 fact ommit add new line operator between printing z , printing m...
you doing:
cout << "same scope of y. @ code! z = " << z; } int m = 20; cout << m; but should do:
std::cout << "same scope of y. @ code! z = " << z << std::endl; } int m = 20; std::cout << m << std::endl; if followed same criteria of labeling output , doing like
std::cout << "m is: "<<m << std::endl; you spotted issue faster observing output:
25m is: 20
Comments
Post a Comment