Trying to setup a graphics C/C++ invironment

Pages: 123
The variables may be 'used' several times ... but only within the 'scope' within which they were declared. In my code x and y happened to be declared inside the { and } delimiting the for-loop and will, indeed, be unknown outside. In fact you could have completely different x and y outside, but that's a whole different story.

There's nothing stopping you declaring x and y "at the top" if you want to; it just isn't necessary in c++.
Variable scope can be one of the harder concepts to grasp when first learning C++, but it is crucial to creating code that doesn't have hard to squash bugs lurking in dark corners waiting to strike.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

int x { 5 };

void MyFunction();

int main ()
{
   int x { 12 };

   std::cout << "x in main(): " << x << "\n\n";

   MyFunction();

   {
      int x { 2238 };

      std::cout << "x in local block in main(): " << x << "\n\n";
   }

   std::cout << "x in main() after local block: " << x << "\n\n";

   std::cout << "global x: " << ::x << '\n';
}


void MyFunction ()
{
   int x { 157 };

   std::cout << "global x: " << ::x << '\n';
   std::cout << "x in MyFunction(): " << x << "\n\n";
}

Same variable name used multiple times, but each new instance is a different variable courtesy of scope.
Topic archived. No new replies allowed.
Pages: 123