代码之家  ›  专栏  ›  技术社区  ›  RhythmInk

c静态范围变量定义不足

  •  0
  • RhythmInk  · 技术社区  · 6 年前

    我的目标是添加(不修改任何现有代码)函数 retrieve() 返回计数器的当前值。

    #include <stdio.h>
    
    void increment(void){
        static unsigned int counter = 0;
    
        counter++;
    
        printf("%d\n", counter);
    
    }
    
    int main(void){
    
        for (int i = 0; i < 5; i++){
            increment();
        }
        
        printf("counter = %d\n", retrieve()); 
    
        return 0;
    }
    

    然而,我尝试的一切都遇到了范围问题。也就是说 counter 尚未实例化,因此编译器将其视为未定义的名称。我尝试添加一个函数

    int retrieve(void){
    
        return counter;
    }
    

    之间 increment 和 main 而且在两者之间 定期的加薪 和 主要的 他们自己我对 static 关键字是,一旦变量被实例化,它将在程序执行长度中保持在定义的块之外。所以我认为我遇到的问题是变量还没有实例化。任何帮助都会很好。

    0 回复  |  直到 6 年前
        1
  •  2
  •   Keith Thompson    6 年前

    范围和生存期是两个不同的东西 一定程度上 独立的

    范围是程序文本中标识符可见的区域。

    Lifetime(或storage duration)是程序执行期间对象存在的持续时间。

    counter ,因为它定义为 static 有 静态存储持续时间 ,这意味着它在程序的整个执行过程中都存在。但是标识符 柜台 有 阻止作用域 ,这意味着该名称仅从其声明到 } 它终止声明它的最内层块。(在这种情况下,该块恰好是函数定义的最外层块。)

        2
  •  0
  •   pm100    6 年前

    您需要将计数器移至全局范围

    #include <stdio.h>
    static unsigned int counter = 0; <<<=========
    void increment(void){
       
    
        counter++;
    
        printf("%d\n", counter);
    
    }
    int retrieve(void){
    
        return counter;
    }
    int main(void){
    
        for (int i = 0; i < 5; i++){
            increment();
        }
        
        printf("counter = %d\n", retrieve()); 
    
        return 0;
    }
    

    公认的最佳实践是以其全球

     unsigned int COUNTER = 0;
    

    或

     unsigned int g_counter = 0;
    
    推荐文章