简体   繁体   中英

Refer to the variable outside block scope but inside function scope ( C/C++)

Hi I wanted to know how to refer to the variable 'x' ( of the main function ) inside the block:

#include <stdio.h>
int x=10;  // Global variable x ---> let it be named x1.

int main()
{
  int x=5;     //  main variable x with function scope ---> let it be named x2.
  for(x=0;x<5;x++)
  {
     int x=2;      // variable x with block scope ---> let it be named x3.
     printf("%d\n",x);   // refers to x3
     printf("%d\n",::x); // refers to x1
     // What is the syntax to refer to x2??? how should I try to access x2?
  }
}
  1. For C

    You cant access x1 in main.Local variables have higher precedence over global variables. x of the main function ie x2 can be accessed outside the for block or before it.

  2. For C++

    C++ has the feature of namespaces by which u can group particular classes/variables..etc into a scope.

So, include the first x1 and x2 in a nested namespace (You can do without it even).

e.g.  namespace a { public : int x; namespace b { public : int x; }  }

   Then to use x1, a::x and to use x2 write a::b:: x;

You cannot refer to x2 in this case. It is declared in a local scope (C does not have the notion of function scope except for labels), and its declaration is masked by the x3 in the inner block. See "local scope" on page 3 in http://www-01.ibm.com/support/docview.wss?uid=swg27002103&aid=1 .

x2 and x3 are the same. The for block is not a scope. When the compiler sees this:

int x = 5;

for(x = 0; x < 5; x++) {
   int x = 2;
}

... it's actually seeing this:

int x;
x = 5;

for(x = 0; x < 5; x++) {
   x = 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM