Why does this compile?

Started by
26 comments, last by GamerSg 20 years, 5 months ago
Thanks to this compiling, i messed up my FYP presentation today when the spells failed to cast.

for(int i=0;i<watever;i++)
{
}
for(int k=0;k<numOfSpellObjs;k++)
{
	if(spellObjs[i].active)
	{
		spellObjs[i].updateAnimation();
	}
}
i is not defined anywhere as a global in my source files. Shouldnt the compiler return an error. When i highlight i and select goto definition, i get a list of 4 header files like commctrl.h, mapidefs.h, wabdefs.h and atlhtml.h where there is a definition of i. But i have not included these files at all. [edited by - GamerSg on October 21, 2003 12:02:15 PM]
Advertisement
What compiler are you using? There''s a bug in Visual C++ 6.0 that does what you described.
Using VS.Net 2002, so i was surprised that it compiled. I tried rebuilding, it still compiles.
Shouldn''t one TEST before a presentation?
shouldn''t one write simple and easily followed code that one KNOWS works - after testing of course
Yeah i should have.

But it had always worked until i made a few changes the night before or maybe in the early morning is a better description.

The spells had always worked and i was extremely tired as i was rushing to compile all the files and burn them. By 2am, the last thing i wanted to do was to go and test something which had always worked. Anyway, the presentation is over and the spells part was the only blunder.

What im concerned is that why the code compiles. With the exception of the 4 header files, which i have not included at all, i is not defined.
i is defined by the first for loop, It hangs around until the end of the block containing the for loop. The same would be true of k. dunno if this is the correct behavior but that''s what it does.
This is an example of Visual C++''s for loop scope conformance deviation. All versions of Visual C++ .NET have a compiler option that allows you to enable proper scoping in for, but it''s disabled by default for each project. Just enable it, and life will be good again.
for(int i=0;i
deleares i. Since its not in any braces its not exclusive to the for loop.

At the time it reached the next for loop i was set to watever.
APE
things declared in a for loop dont exactly act like you would think, their scope isn't the for loop, it's the block the for loop is in. (vc++ specific, im unsure about other compilers)
void main(){  for(int i=0;i<2;i++)  {     for(int j=0;j<2;j++)     {     }  }  for(int i=0;i<2;i++)//error, i already exists within this scope  {     for(int j=0;j<2;j++)// but j is ok     {     }  }}  


[edited by - Raptor85 on October 21, 2003 12:13:30 PM]

This topic is closed to new replies.

Advertisement