Advertisement

Attempting a proper 2D game engine, always find myself out-of-scope

Started by October 21, 2016 10:53 PM
10 comments, last by Oberon_Command 8 years, 1 month ago


I thought while loops were different, because I can declare something immediately prior to the while loop, and access that data from within the while loop without needing to pass a value or reference.

Variable declaration outside also work with for and do loops. It is not constrain to while.



I thought while loops were different, because I can declare something immediately prior to the while loop, and access that data from within the while loop without needing to pass a value or reference.

Variable declaration outside also work with for and do loops. It is not constrain to while.


Could you give more details what problem gets solved by the 'while' ? (or even why the problem with the 'ranged loop' doesn't happen with 'while').


I've likely got the wrong idea in my head - I thought that scopes were handled differently (while versus for). A for-loop has its own scope/namespace, like a virtual container within the program, the same thing with functions. I thought while loops were different, because I can declare something immediately prior to the while loop, and access that data from within the while loop without needing to pass a value or reference.


If something is declared outside a particular scope, it will be visible to scopes declared within that scope.


int x = 0;

void function1()
{
   // works because x is a global - declared outside function1
   x = 2;
   int y = x;
   for (int i = 0; i < 5; i++) 
     y *= i; // works, y is a local outside the scope of the for statement and i is within it

   // does NOT work, i is local to the for
   x = x * i;
}

This topic is closed to new replies.

Advertisement