[英]Does a const variable behave like a static variable when defined in a C++ function?
我有一个小问题。 在 C++ 中,在函数中定义一个 const 整数是否合法和/或明智,其值取决于函数的输入参数? 如果是,该值是否在函数内保持不变并随着对具有不同参数的函数的不同调用而变化,或者它是否像静态变量一样在整个程序的范围内保持不变?
这是我在代码中的意思的快速示例。
void testMyVar(int x, int y){
const int z = x/y;
//use z for whatever computation
}
提前感谢您的帮助!
声明为const
的变量一旦初始化就不能修改。
在这种情况下,当函数被输入时, z
被初始化为x/y
的值,并将在函数运行期间保持该值。 每次调用该函数时, z
都将使用传递的x
和y
的任何值进行初始化。
没有与static
相关的行为,因为变量未声明为static
。
意识到 z 一旦超出范围就会被“销毁”,因为它不是static
。 如果 z 在函数范围内或嵌套在 if/for/if 中的 3 层深处,则为真
static int z = 42; // I will label this z0
void testMyVar(int x, int y) {
const int z = x/y; // I will label this z1; this z is different than the static z above (z0)
if (z > 10) { // tests z1, not z0
int z = x; // non-const z; I will label this z2, which is different than z1 and z0
z++; // C++ uses inner-most scoped z (so here, it's z2), so this is good (non-const)
for (int i = 0; i < z; i++) {
int z = i / 2; // I will label this z3, it gets re-evaluated every time through the for loop
z = z * z; // all 3 z refererences here is z3
cout << z << endl; // dumps z3
cout << ::z << endl; // dumps z0 note the global scoping operator ::
} // z3 gets "destroyed"
} // z2 gets "destroyed"
} // z1 gets "destroyed
C++ 语法不提供在不同代码范围(仅在全局、类/结构和名称空间)指定命名变量范围的机制。 因此,您不能在定义更深 z 的 z2/z3 的代码嵌套级别中专门使用顶级 const int z(我标记为 z1)。 请注意,我可以通过使用全局范围运算符::
在 z3 级别引用“全局”范围内的静态 z ::z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.