View Single Post
Re: which one is "standard"...
Old
  (#5)
botman
Super Moderator
 
Status: Offline
Posts: 280
Join Date: Jan 2004
Location: Plano, TX
Default Re: which one is "standard"... - 16-05-2004

It depends on what YOU want the scope of the variable 'i' to be. If you only want it to be valid inside the 'for' loop then the first one is "standard" (according to ANSI standards for C++).

If you want to know what the value of 'i' was below the 'for' loop you'd need to use the second case. For example, you could have something like this...
Code:
int i;
for (i = 0; i < 10; i++)
{
   if (i == x)
	  break;
   printf("i is %d\n", i);
}
if (i == 10) // did the loop finish or break out early?
   printf("the loop executed 10 times\n");
The third example you should would be if you wanted to create a local scope for 'i' that included the 'for' loop and some amount of code below the loop.

NOTE: Microsoft Visual C++ 6.0 doesn't adhere to the same ANSI standards as gcc. So, for example, this code is perfectly valid in MSVC 6.0, but not in gcc...
Code:
for (int i=0; i < 10; i++)
   printf("i = %d", i);
if (i == 10) // NOT VALID IN GCC SINCE 'i' SHOULDN'T EXIST HERE!!!
   printf("the loop executed 10 times\n");
MSVC 7.0 and 7.1 are more ANSI compliant than MSVC 6.0

botman

Last edited by botman; 16-05-2004 at 15:16..
  
Reply With Quote