I know there are plenty of answers out there but non of them cleared my doubt... C++ standard says:
The
forstatementfor ( init-statement condition ; expression ) statementis equivalent to
{ init-statement while ( condition ) { statement expression ; } }except that names declared in the init-statement are in the same declarative-region as those >declared in the condition (which is also the scope of statement).
It means if I declare a variable inside the init-statement, then that variable will be in the same scope as that of statement and the statement executes in each iteration... now, my question is:
- Does variable declaration in init-statement also executed in each iteration?
for eg:
for(int i = 0; i < 5; i++){
int number = 2; // this will be executed in each iteration
}
Now, as standard says 'i' variable will also be in the same scope of 'number' so does it also destroyed and declared at each iteration like 'number'?
PS: but it can't be because standards also says that init statement executes one and only once before the condition statement.. I just want to know the reason and how things work?
EDITED
for(int i=0; i<10; i++){
int num = 2;
}
acc. to the standards The 'i' variable and the 'num' variable both are in the same scope then how 'i' variable is declared only once and num variable declared repeatedly (here 10 times), I mean if they both are in the same scope isn't 'i' variable too destroyed and declared 10 times like 'num'...(I know it may sound silly but it is confusing me a lot)