我正在尝试解决 Effective C 第 2 章中的练习 1 ,它说:
“向 list 2-6 中的计数示例添加检索函数以检索计数器的当前值”
list 2-6 中的代码是:
#include <stdio.h>
void increment(void) {
static unsigned int counter;
counter++;
printf("%d ", counter);
}
int main(void) {
for (int i = 0; i < 5; i++) {
increment();
}
return 0;
}
我已经尝试了几件事但都失败了,我不明白如何检索计数器的值,因为在增量函数之外它超出了范围并且没有可以使用的指针。
最佳答案
我会将计数器
和检索或更新其值的函数分开。为此,我会将 counter
转移到文件范围并使其对其他翻译单元不可见(即 static
):
static unsigned int counter;
void increment(void) {
counter++;
}
unsigned int getCounter() {
return counter;
}
// usually in a separate translation unit
int main(void) {
for (int i = 0; i < 5; i++) {
increment();
printf("%d ", getCounter());
}
return 0;
}
关于c - 在 C 中,如何在没有指针的情况下检索超出范围的静态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65522309/