[try Beta version]
Not logged in

 
Quick int for loops

May 22, 2013 at 9:40am
Quick question!

Is this...

1
2
3
4
for ( int i = 0; i < 10; i++ )
{
...blah blah code...
}


the same as this...

1
2
3
4
5
int i;
for ( i = 0; i < 10; i++ )
{
...blah blah code...
}
May 22, 2013 at 10:09am
The only difference is that i will be in scope, and can be reused, after the loop.
May 22, 2013 at 10:15am
In C++03 there isn't any difference (Aside from non-intuitive scope of i in first case).
In C++11 it is as Peter87 said.
Last edited on May 22, 2013 at 10:49am
May 22, 2013 at 10:38am
@MiiNiPaa
C++03 or C++11 doesn't matter. The rules has not changed.
Last edited on May 22, 2013 at 10:40am
May 22, 2013 at 10:49am
Yes sorry, googled that. It is Visual C compiler which violates standard.
May 22, 2013 at 1:15pm
Visual Studio's compilers have flags for both standard conformance and MS extensions. The default is something. To be fair, GCC's default mode is to enable GNU extensions rather than strict standard.
May 22, 2013 at 1:35pm
Yes, they do, but up intil recent versions ANSI mode was unusable as many headers provided with compiler weren't compatible with it.
I actually dislike when different extensions are enabled by default (GCC valarray support, MS "Threat use of non-ms-specific c-string manipulation functions as error" (or warning, I don't remember)) and GCC defaults to C++03 mode.
Last edited on May 22, 2013 at 1:38pm
May 22, 2013 at 2:46pm
As Peter87 said

The only difference is that when you declare i before the loop, it can be reused throughout the function it is in whereas, when you declare it within the loop. It can only be used within that loop, and if you attempted to call it outside of the loop you would get a compiler error stating that it is an undeclared variable.
May 23, 2013 at 7:46am
Thanks very much guys, ill take that into consideration when writing my code!
Topic archived. No new replies allowed.