首页 > 解决方案 > 如何在 C 中拥有一个在被任何函数使用时递增的全局变量

问题描述

我试图有一个全局计数器,程序中的任何函数都可以使用它。这可能吗?

int* count;

main(){
   *count = 0;
}

void incrementCount(){
   ++*count;
}

int getCount(){
   return *count;
}

如果不可能,我该怎么做类似的事情?

标签: cpointersglobal-variables

解决方案


不需要带指针。取一个变量,如

int count;

如果您打算在单个文件中使用它,最好声明它static

更好的方法是使用 getter 和 setter 函数,而不是到处更新全局变量


推荐阅读