5

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: } 
2
  • 3
    These are two different variables, because the for block creates a new scope. Commented May 11, 2015 at 22:11
  • 1
    Try printing fly after the loop and you'll see that it's still 0. Commented May 11, 2015 at 22:12

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.