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

标签 c scope static

我正在尝试解决 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/

相关文章:

返回函数的 Javascript 作用域错误函数

javascript - 如何使用链式 javascript 原型(prototype)继承?

html - Rails 4 静态公共(public) index.html

c++ - AVX 将 64 位整数转换为 64 位 float

c - 从函数返回数组地址无效

c - 需要有关 Windows Journal Record Hook 的帮助

javascript - 嵌套的 Angular http.get 调用

java - 静态初始化 block 的设计问题

java - 在java中设置静态对象

c - 使用 struct stat 在 tar 的 header 中获取文件的权限