简体   繁体   English

C ++声明变量两次

[英]C++ declaring a variable twice

Hello everyone I am learning about the declaration of variables in C++. 大家好我正在学习C ++中的变量声明。

Now please tell me my mistake here. 现在请告诉我我的错误。 Why is it bad to declare your variable twice? 为什么两次声明变量不好?

int fly = 0;

for(int fly = 0; fly < 10; fly++) {
    cout << "This is a kite flying" << fly << endl:
}

These are two seperate variable because they are declared in a different scope . 这是两个单独的变量,因为它们在不同的范围内声明。 The scope of a variable is the "area" of code in which it's visible. 变量的范围是可见的代码“区域”。

As a simple rule of thumb, any place where curly brackets are, or could be placed, is a new scope. 作为一个简单的经验法则,大括号是或可以放置的任何地方都是新的范围。 The fly inside the for loop, overrides the other fly variable. fly for循环内,将覆盖其他fly变量。 If it wasn't declared, or declared under a different name. 如果没有声明,或以不同的名称声明。 The original variable would still be accessible. 原始变量仍然可以访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM