c - 引用 block 作用域外但函数作用域内的变量 (C/C++)

标签 c reference scope

您好,我想知道如何在 block 内引用变量“x”(主函数的):

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

    您不能在 main 中访问 x1。局部变量比全局变量具有更高的优先级。 主函数的 x,即 x2 可以在 for block 之外或之前访问。

  2. 对于 C++

    C++ 具有命名空间的特性,您可以通过命名空间将特定的类/变量等分组到一个范围内。

因此,在嵌套命名空间中包含第一个 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;

关于c - 引用 block 作用域外但函数作用域内的变量 (C/C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20165680/

相关文章:

c++ - 程序在开始第二个输入流之前终止

regex - Perl 中 $1 到 $9 的范围是什么?

java - 如何在 Java 中从包含数字的文件创建数组?

JavaScript - 未捕获的 ReferenceError : checkAnswer is not defined, 函数不在范围内?

c++ - 为什么当我输入三月或七月时,我的代码没有给出正确的输入?

c++ - libpq VS qpsql(postgre 的 QT 驱动程序)

loops - 循环时,.iter() 与引用 (&) 有何不同?

c - 将数据发送到等待 ppoll 的另一个进程的 stdin

c - C 中的变量不显示?

c# - Xamarin.Android nuget 包引用 System.Web