extremely local variable, or not?

Mar 15, 2011 at 10:12pm
I've just been wondering, if I do:

1
2
3
4
5
if(rand() % 3 == true)  
{ // make w super-local by using a brace, yes           
    for(int w = 0; w < 4 ; w ++)
        Factor7_wheelcheese[w] = rand() %2;
}

that would result in a guaranteed extremely-local variable.

But what about this:

1
2
3
4
if(rand() % 3 == true)  
    for(int w = 0; w < 4 ; w ++) // could well be local to nearest other brace 
        Factor7_wheelcheese[w] = rand() %2;
        

thanks in advance for in-the-know replies! -B

Edit: I am referring to int w as the local-to-loop-and-if variable, not Factor7_wheelcheese[]. thanks for the replies.
Last edited on Mar 16, 2011 at 2:15pm
Mar 15, 2011 at 10:29pm
it's local to the outermost curly braces where it was declared. unless i'm missing something, there is no variable declaration (other than int w) in either of those blocks of code. if Factor7_wheelcheese[w] = rand() %2; is somehow a variable declaration that i don't understand, though, i's local to the for loop in both pieces of code
Mar 15, 2011 at 10:33pm
1
2
3
4
5
if(rand() % 3 == true)  
{           
    for(int w = 0; w < 4 ; w ++)
        Factor7_wheelcheese[w] = rand() %2;
}


The scope of the w variable is the scope of the for loop - which means these two lines:
1
2
    for(int w = 0; w < 4 ; w ++)
        Factor7_wheelcheese[w] = rand() %2;


So this:
1
2
3
if(rand() % 3 == true)  
    for(int w = 0; w < 4 ; w ++) // 
        Factor7_wheelcheese[w] = rand() %2;

is the same as the first set of code


**Note: Microsoft VC 6 is defective in this aspect, because w would have scope all the way to the end of the function - this is a known problem with this compiler**



Mar 15, 2011 at 10:33pm
Firstly, may I ask exactly what an 'extremely local variable' is. I have never heard this term before.

I may be wrong, but aren't those two code segments exactly the same? The omission of braces in the second line is merely a convenience, isn't it? I shouldn't think that it makes any difference to the actual compiled code.

In both cases, I think the variable int w is only alive for the duration of the for loop.

EDIT: Whoops. Look like you beat me to it guestgulkan!
Last edited on Mar 15, 2011 at 10:34pm
Topic archived. No new replies allowed.