c - 如何在 C 中拥有一个在被任何函数使用时递增的全局变量
问题描述
我试图有一个全局计数器,程序中的任何函数都可以使用它。这可能吗?
int* count;
main(){
*count = 0;
}
void incrementCount(){
++*count;
}
int getCount(){
return *count;
}
如果不可能,我该怎么做类似的事情?
解决方案
不需要带指针。取一个变量,如
int count;
如果您打算在单个文件中使用它,最好声明它static
。
更好的方法是使用 getter 和 setter 函数,而不是到处更新全局变量
推荐阅读
- php - 在 Laravel 5.8 中验证 .tar 文件上传
- python - 在 Python 中的映射迭代期间替换值是否安全?
- javascript - 如何在没有域的情况下获得 socket.io 的证书(我不喜欢自签名)
- r - R 时间序列数据,按正比分组
- flutter - Flutter SingleChildScrollView 在 Stack 中不起作用
- reactjs - 如何将 TypeScript 与 React / Redux mergeProps 一起使用
- r - How to copy a value in new dataframe based on key links of another dataframe like ID, start and end value? (in R)
- php - Php PDO Mysql 选择值下拉列表
- html - WordPress。使整个 div 类可点击
- shopify - 如何使用 Shopify API 取消和补货?