the 5th output comes from the call to b(); b() doesn't have a local x defined so it takes the global x which you defined as 1. The last output just takes the x local to main() which is still 5;
[code]
1x = 5 // x is local to main
2x = 7 // x is local to bracketed segment inside main
3x = 5 // x is local to main
4x = 25 // x is local to a()
5x = 1 // x is global
6x = 5 // x is local to main
[code]
You can't work with functions unless you understand the concept of scope. Start with the tutorial page above and then do some searching. There's no point asking for an explanation here as namespaces are common to most computer languages so there are thousands of tutorials on the subject readily available.
The "global" x is so because it is declared outside of all of the other functions and organizational blocks. The x inside main is "local" to main because functions outside of main cannot access it. The x declared in a() is created when a() is called and destroyed when a() returns so nothing outside of a() can access it.
#include <iostream>
int x = 0; // global variable can be accessed by any function in this unit (cpp file)
void alter_global(int x) { ::x = x; } // assigning global x the value of x passed to function
void print_x(int x) { std::cout << x << std::endl; } // printing x passed to function
void local_function() { int x = 10; print_x(x); print_x(::x); } // printing local x then global x (lines 4 and 5 on output)
int main()
{
int x = 5;
print_x(x); // print local x (line 1 on output)
print_x(::x); // print global x (line 2 on output)
alter_global(99); // change global x to 99
print_x(::x); // print global x (line 3 on output)
local_function();
return 0;
}
The output for the code above is this:
1 2 3 4 5 6 7 8
5
0
99
10
99
Process returned 0 (0x0) execution time : 0.047 s
Press any key to continue.