C ++ declares variable twice

Hello everyone that I learn about variable declarations 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:
}

      

+3


source to share


1 answer


They are two separate variables because they are declared on a different scope . The scope of a variable is the "area" of the code in which it is displayed.



As a simple rule of thumb, any place where curly braces are, or can be placed, is a new region. fly

inside the for loop, overrides another variable fly

. Unless announced or announced under a different name. The original variable will still be available.

+6


source







All Articles