Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring and initializing variable in for 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?)

like image 469
user Avatar asked Jul 06 '10 18:07

user


People also ask

Can you initialize variables in a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

How do you declare a variable in a loop?

Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.)

What is initialization in a for loop?

The initialization is an expression that initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false , the loop terminates.

What is declaring and initializing variables?

Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.


3 Answers

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.
like image 181
Martin York Avatar answered Oct 20 '22 20:10

Martin York


Yes, it's legal in C++ and in C99.

like image 21
Nikolai Fetissov Avatar answered Oct 20 '22 20:10

Nikolai Fetissov


It's perfectly legal to do this in C99 or C++:

for( int i=0; i<max; ++i )
{
    //some code
}

and its while equivalent is:

{
    int i=0
    while( i<max )
    {
        //some code
        ++i;
    }
}
like image 29
rubenvb Avatar answered Oct 20 '22 21:10

rubenvb