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?)
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.
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.)
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.
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.
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.
Yes, it's legal in C++ and in C99.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With