我每次从函数返回时都可以重置全局变量的值

OMG*_*OMG -3 c variables global function

我想要一个函数应该每次返回时将全局变量值重置为0.

我知道我可以gVar=0;在每个return语句之前添加,但这不是我想要的方式,因为新开发人员可能没有这些信息并且可能无法重置gVar值.

要求是

global int gVar = 10;
void fun() 
{
 // Need to modify gVar Here 
  gVar = 15;
  .
  .
  .
  gVar = 20;
  if (some condition)
         return;
  else 
         return; 
..
// more return possible from this function 
// also new developer can add more return statement 
// i want every time function return it should set gVar=0
} 
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 7

创建一个析构函数设置gVar为0 的类,然后在函数的开头声明它的实例.当函数返回时,变量超出范围并调用析构函数.

class ClearGVar {
public:
    ClearGVar() {}
    ~ClearGVar() { gVar = 0; }
}

void fun()
{
    ClearGVar x;
    ...
} 
Run Code Online (Sandbox Code Playgroud)

编辑:

发布后删除了C++标记.在C.中没有好办法做到这一点.