Declaring and initializing variable in for loop

2019-06-15 18:26发布

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?)

7条回答
做自己的国王
2楼-- · 2019-06-15 19:02

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

查看更多
Bombasti
3楼-- · 2019-06-15 19:03

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.

查看更多
我只想做你的唯一
4楼-- · 2019-06-15 19:04

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;
    }
}
查看更多
【Aperson】
5楼-- · 2019-06-15 19:04

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

查看更多
家丑人穷心不美
6楼-- · 2019-06-15 19:16

Its 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.
查看更多
劫难
7楼-- · 2019-06-15 19:27

if you use variable out side the loop it will be change every time when you initialize it inside loop

int i = 0;
for(int e = 0; e < 10; e++)
{
 i = e;
}

now i value will change every time

查看更多
登录 后发表回答