简体   繁体   English

请参阅块范围之外的变量,但函数范围之内(C / C ++)

[英]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: 嗨,我想知道如何在块内引用变量“ x”(main函数的):

#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 对于C

    You cant access x1 in main.Local variables have higher precedence over global variables. 您不能在main中访问x1。局部变量的优先级高于全局变量。 x of the main function ie x2 can be accessed outside the for block or before it. 主要功能的x即x2可以在for块之外或之前访问。

  2. For C++ 对于C ++

    C++ has the feature of namespaces by which u can group particular classes/variables..etc into a scope. C ++具有名称空间的功能,通过该名称空间,您可以将特定的类/变量..etc分组为一个范围。

So, include the first x1 and x2 in a nested namespace (You can do without it even). 因此,将第一个x1和x2包含在嵌套的命名空间中(甚至可以不使用它)。

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. 在这种情况下,您不能引用x2。 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. 它在局部范围内声明(C除了标签外没有函数范围的概念),并且其声明被内部块中的x3掩盖。 See "local scope" on page 3 in http://www-01.ibm.com/support/docview.wss?uid=swg27002103&aid=1 . 请参阅http://www-01.ibm.com/support/docview.wss?uid=swg27002103&aid=1中第3页的“本地范围”。

x2 and x3 are the same. x2x3相同。 The for block is not a scope. for块不是作用域。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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