简体   繁体   English

基本的c问题-在c中声明静态变量时会发生什么?

[英]Basic c question - What exactly happens when you declare a static variable in c?

I'm trying to learn how static variable work in c for when they are defined in a given function. 我正在尝试学习在给定函数中定义静态变量时在c中如何工作。 For example, when I write the following: 例如,当我编写以下代码时:

#include <stdio.h>
void inc() {
  static int c = 0;
  c++;
  printf("%d\n", c);
}

int main(void) {
  inc();
  inc();
  inc();
  return 0;
}

The expected output is obviously: 预期的输出显然是:

1
2
3

On the first call of the function, the static variable c is defined and given the value of 0, which makes perfect sense. 在第一次调用该函数时,将定义静态变量c并将其值设为0,这是很合理的。 It is the incremented and printed. 它已递增并打印。 However, on the second call to inc() why is it that the integer c is maintained and not set to zero, even though the code literally says static int c = 0; 但是,在第二次调用inc()为什么即使代码字面上说static int c = 0;整数c仍被保留而不设置为零;为什么static int c = 0; . What mechanism in the compiler stops c from having it's value set to zero like during the first call? 像第一次调用期间一样,编译器中的哪种机制阻止c将其值设置为零?

Quoting C11 , chapter §6.2.4, Storage durations of objects ( emphasis mine ) 引用C11 ,第§6.2.4章,对象的存储期限( 重点是我的

An object whose identifier is declared without the storage-class specifier _Thread_local , and either with external or internal linkage or with the storage-class specifier static , has static storage duration . 声明其标识符时没有存储类说明符_Thread_local且具有外部或内部链接或具有存储类说明符static ,其存储时长为静态 Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup. 它的生命周期是程序的整个执行过程,并且在程序启动之前,它的存储值仅初始化一次。

So, the initialization inside the function call does not take place on every call to the function. 因此,函数调用内部的初始化不会在对函数的每次调用中进行。 It only happens once, before the execution of main() starts. main()开始执行之前,它仅发生一次。 The variable retains the last stored value through the program execution, ie, the value is retained between the repeated calls to the function. 该变量在程序执行过程中保留最后存储的值,即,在重复调用函数之间保留该值。

它的生命周期是程序的整个执行过程,并且其值在程序启动之前被初始化并且只有一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM