如何在C中没有指针的情况下检索超出范围的静态值?

我正在尝试解决Effective C第 2 章中的练习 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;
}

我尝试了几件事但失败了,我不明白如何检索计数器的值,因为在增量函数之外它超出了范围并且没有可以使用的指针。

回答

我会将counter检索或更新其值的函数和函数分开。为此,我会将counterto 文件范围转移并使其不可见(即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中没有指针的情况下检索超出范围的静态值?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>