Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ declaring a variable twice

Tags:

c++

Hello everyone I am learning about the declaration of variables in 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:
}
like image 416
Leouret Avatar asked Feb 11 '23 04:02

Leouret


1 Answers

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. If it wasn't declared, or declared under a different name. The original variable would still be accessible.

like image 121
laurisvr Avatar answered Feb 23 '23 11:02

laurisvr