C 中的全局和局部变量
Global and local variables in C++
我是C 的新手,在打印本地和全局变量时,我会遇到一些问题。考虑这件简单的代码:
#include <cstdlib>
#include <iostream>
using namespace std;
/*
*
*/
int x = 10; // This x is global
int main() {
int n;
{ // The pair of braces introduces a scope
int m = 10; // The variable m is only accessible within the scope
cout << m << "n";
int x = 25; // This local variable x hides the global x
int y = ::x; // y = 10, ::x refers to the global variable x
cout << "Global: " << y << "n" << "Local: " << x << "n";
{
int z = x; // z = 25; x is taken from the previous scope
int x = 28; // it hides local variable x = 25 above
int t = ::x; // t = 10, ::x refers to the global variable x
cout << "(in scope, before assignment) t = " << t << "n";
t = x; // t = 38, treated as a local variableout was not declared in this scope
cout << "This is another 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 the same scope as y
cout << "Same scope of y. Look at code! z = " << z;
}
//i = m; // Gives an error, since m is only accessible WITHIN the scope
int m = 20; // This is OK, since it defines a NEW VARIABLE m
cout << m;
return 0;
}
我的目标是练习各个范围内变量的可访问性,然后打印它们。但是,我无法弄清楚为什么当我尝试打印最后一个变量z
时,NetBeans会给我提供输出2025
。在这里,它遵循我的样本输出:
10
Global: 10
Local: 25
(in scope, before assignment) t = 10
This is another hidden scope!
z = 25
x = 28
(in scope, after re assignment) t = 28
Same scope of y. Look at code! z = 2520
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
希望有人可以帮助我了解发生了什么!:)
不是 z> z 保持值 2520 是您要添加的事实是,您可以在printing z 和打印 m ...
您正在做:
cout << "Same scope of y. Look at code! z = " << z;
}
int m = 20;
cout << m;
但是您应该这样做:
std::cout << "Same scope of y. Look at code! z = " << z << std::endl;
}
int m = 20;
std::cout << m << std::endl;
如果您只是遵循标签输出并执行
的相同标准std::cout << "M is: "<<m << std::endl;
您会通过观察输出来更快地发现问题:
25M is: 20
相关文章:
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 使用全局变量与局部变量和require
- 将变量声明为全局变量,然后声明为局部变量 -Shadowing-
- 将局部变量保存到全局向量中,为什么离开局部范围后可以得到这些局部变量?
- 局部变量如何隐藏全局变量
- 编译器是否可以从全局变量中读取两次,而不是存储一个局部变量
- 我不知道如何让我的程序使用局部变量而不是全局变量
- 怎么可能有两个同名的变量——一个是全局变量,另一个是局部变量
- 递归计算在不使用静态局部变量,全局变量或静态函数的情况下,在递归函数中发生的环数
- C 中的全局和局部变量
- 初学者程序员 c++(局部与全局变量声明)
- Arduino/C++全局变量与局部变量
- c和c++上下文中静态、自动、全局和局部变量之间的差异
- 编译器如何知道变量是全局变量还是局部变量(C)
- 当局部变量被复制到全局变量时,C++GCC优化速度会减慢
- 为什么局部变量不隐藏数组定义中的全局变量
- 全局变量和局部变量
- C++:全局变量与局部变量.使用什么
- C++-全局变量与局部变量的读/写速度