我正在尝试解决Effective C第二章中的练习1,它说:
“向清单2-6中的计数示例添加检索函数,以检索计数器的当前值”
清单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;
}
我尝试了几件事都失败了,我不明白如何检索计数器的值,因为在增量函数的外部它超出了作用域,并且没有可以使用的指针。
发布于 2020-12-31 23:39:34
我将counter
和检索或更新其值的函数分开。为此,我将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;
}
发布于 2020-12-31 23:01:00
使用return,您可以这样做:
#include <stdio.h>
unsigned int increment(void)
{
static unsigned int counter;
counter++;
return counter;
}
int main(void)
{
for (int i = 0; i < 5; i++)
{
printf("%u ", increment());
}
return 0;
}
https://stackoverflow.com/questions/65522309
复制相似问题