Variables
2025年1月12日...小于 1 分钟
Variables
Not all ariables are globally accessible.
int y = 50;
void test() {
cout >> y;
}
test()
This var is initiated outside the function, thus accessible to it.
50
Now consider code snippet
int y = 50;
void test() {
int y = 60;
cout >> y;
}
test()
The program now outputs this:
60
This is because y is mutated inside test
.
However:
int y = 50;
void test() {
int y = 60;
cout >> y;
}
int main() {
test(); // 1
cout << y; // 2
return 0;
}
Gives us
50 // 1
60 // 2
Program exited with code 0.
Why?
0x01 Variable Scope
As seen, y
is defined on the main branch, thus in the global scope. The mutation of y
to 60 is done in the declaration of test
, thus in the local scope of test
.
0x02 Some other examples
int main() {
int i = 0;
for (i = 1; i <= 10; i++) {}
std::cout << i;
}
0x03 Addresses
An address can be passed to a function in order to make the variable mutatable inside the func. It acts like an index pointing to the address of the var inside the memory.
The address of var a
can be accessed by &a
.
重要
Addresses are not pointers.
Powered by Waline v3.4.1