Handmade Hero»Forums»Code
Pete
22 posts
Variable scope in old C
Edited by Pete on Reason: Code formatting
I am working on a project where there is a lot of old code written for Windows.

On several places in the code i run in to the following situation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
for(int i=0;i < 10; i++)
{
    // does stuff
}

// a couple of lines

for(i=0; i < 20; i++)
{
    // does stuff with variable i that was declared in the previous for-loop
}


The compiler throws an error at me saying i is not declared for the second for-loop. I am willing to agree with the compiler.

But since this code has been around for a long time I am suspecting that this actually worked at some time.

My question is if this was a thing in old-style C or C++? For me it looks really odd.

Sorry for getting off the topic of Handmade hero in this post I just thought this was a good forum to ask this type of question.

Also, love this project and I want to thank Casey for clarifying so much stuff.
Asaf Gartner
64 posts / 2 projects
Handmade Network Staff
Variable scope in old C
That used to be valid code. That's why you can see Casey doing for loops like this in some early videos:
1
2
3
{for(int i = 0; i < 10; ++i)
{
}}

That way the `i` is guaranteed not to stick around after the for loop.
Mārtiņš Možeiko
2561 posts / 2 projects
Variable scope in old C
Edited by Mārtiņš Možeiko on
It was valid code only with Visual Studio. In C that was never a valid code.
Not sure how far back it goes, but Visual Studio 6 allowed that. Starting with next version of Visual Studio (2005) they disabled this behavior by default.

You can still enable old behavior by using /Za, /Zc, /Zc:forScope compiler argumnets - https://msdn.microsoft.com/en-us/library/84wcsx8x.aspx Even in latest Visual Studio 2015.

Another "trick" some people used to avoid this behavior in old VS6 was to redefine for keyword:
1
#define for if (0) {} else for

This forces compiler to put for variable in scope of else statement and it doesn't go outside of it.
Pete
22 posts
Variable scope in old C
Thank you for the clear answers. Now I know why it looks this way and that i can make my changes without worrying to much that i brake something else.