gpt4 book ai didi

c++ - 为什么这个 c++ 有效? (具有相同名称的变量)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:45 25 4
gpt4 key购买 nike

好吧,我想知道为什么这段代码有效,我刚刚意识到我在同一范围内有两个同名的变量。

我正在使用 g++ (gcc 4.4)。

for(int k = 0 ; k < n ; k++)
{
while(true)
{
i = Tools::randomInt(0, n);
bool exists = false;

for(int k = 0 ; k < p_new_solution_size ; k++)
if( i == p_new_solution[k] )
{
exists = true;
break;
}
if(!exists)
break;
}

p_new_solution[p_new_solution_size] = i;
p_new_solution_size++;
}

最佳答案

内部 for 循环中的 k 隐藏(或隐藏)外部 for 循环中的 k

您可以在不同范围内声明多个具有相同名称的变量。一个非常简单的例子如下:

int main()
{
int a; // 'a' refers to the int until it is shadowed or its block ends
{
float a; // 'a' refers to the float until the end of this block
} // 'a' now refers to the int again
}

关于c++ - 为什么这个 c++ 有效? (具有相同名称的变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4151203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com