Does C supports scope resolution? [duplicate]

瘦欲@ 提交于 2020-01-05 09:28:05

问题


    #include <stdio.h>

/* global variable declaration */
int g = 20;

int main ()
{
  /* local variable declaration */
  int g = 10;

  printf ("value of g = %d  %d\n",  g,::g);

  return 0;
}

When i am trying to run this program. It is throwing error main.c:11:39: error: expected expression before ':' token printf ("value of g = %d %d\n", g,::g);. But if it is written in C++, it works fine.


回答1:


No, that's a C++ feature. In C, declaring a variable in an inner scope will hide the one in the outer scope.

If you must do it, you can use pointers to get at the outer scope but it's a bit of a kludge and not something I'd recommend:

#include <stdio.h>
int g = 20;
int main () {
  int *pGlobalG = &g;
  int g = 10;
  printf ("value of g = %d %d\n", g, *pGlobalG);
  return 0;
}


来源:https://stackoverflow.com/questions/21201788/does-c-supports-scope-resolution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!