Declaration of a variable inside loop

Hello I want to know that if I declare a variable during initialization inside a loop.

for(int i =0; condition; inc/dec)

So now why I need to declare it again inside another loop.

Hey @yashsharma4304
Can you please share the exact code of whatever u are talking about.

ok let me try to write a code to ask my doubt.

https://ide.codingblocks.com/s/357296

So this is my code. Here in this code there are two loops. First one will execute 2 times and another loop execute 3 times. In both loops I used same variables that is i.

Now when I execute my program it says “i was not declared in this scope” for second loop which run three times.

Hey @yashsharma4304
Okay so this is because whatever variable u declare inside loop or in loop conditions is local to the loop and is valid inside { body } of loop only
And is not accessible as soon as loop ends.

If the loops are nested

for(int i..)
{  //Xst
     for(int j...){ //Yst
                 ...
      }//Yend
}  //Xend

Here i is accessible anywhere between Xst and Xend
And j is accessible between Yst and Yend

1 Like

Ok so its a local variable for a loop and can be accessed only inside the body of that loop. So this is the concept of scope of variables. Right?

Yes its …

Say u have

int main(){
   
//onlly bracket block 
  {
     int j=5;
  }
cout<<j;//this will give error too because j scope ended 

}
1 Like

Ok so the variable can also be locally defined inside curly brackets.

Yes …

Ok thank you for clearing my doubt. And also for providing the extra knowledge.

1 Like