C++ – Declaring and Initializing Variable in a For Loop

c++declarationfor-loop

Can I write simply

for (int i = 0; ...

instead of

int i;
for (i = 0; ...

in C or C++?

(And will variable i be accessible inside the loop only?)

Best Answer

It's valid in C++.

It was not legal in the original version of C.
But was adopted as part of C in C99 (when some C++ features were sort of back ported to C)
Using gcc

gcc -std=c99 <file>.c

The variable is valid inside the for statement and the statement that is looped over. If this is a block statement then it is valid for the whole of the block.

for(int loop = 0; loop < 10; ++loop)
{
    // loop valid in here aswell
}

// loop NOT valid here.