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?)
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;
}
}
Acutally for(int i=0;i<somevalue;i++)
was always drilled into me as the preferred way to define a for loop in c and c++.
As far as "i" only being accessible in your loop, you have to be care about the variable names you use. If you declare "i" as a variable outside of the loop and are using it for something else then you are going to cause a problem when using that same variable for a loop counter.
For example:
int i = 10;
i = 10 + PI;
will be automatically changed when you hit the for loop and declare i=0
Yes and yes. But for C, apparently your compiler needs to be in C99 mode.
Can I write simply
Yes.
(And will variable i be accessible inside the loop only?)
Depends on the compiler and its' version. AFAIK, in modern compilers i is accessible inside of the loop only. Some older compilers allowed i to be accessible outside of loop as well. Some compilers allow i to be accessed outside of the loop and warn you about non-standard behavior.
I think (but I'm not sure about it), that "i outside of the loop" was used somewhere in VC98 (Visual Studio 6, which AFAIK, also had a globally defined "i" variable somewhere that could lead to an extremely interesting behavior). I think that (microsoft) compilers made somewhere around around 2000..2003 started printing "non standard extensions used" for using i outside of loop, and eventually this functionality disappeared completely. It isn't present in visual studio 2008.
This is probably happened according to a standard but I cannot give a link or citation at the moment.
If you use the variable outside the loop, it will be changed every time you initialize it inside loop.
int i = 0;
for(int e = 0; e < 10; e++)
{
i = e;
}
Now, the value of i
will change every time.
精彩评论