c static 问题

来源:互联网 发布:海康 知乎 编辑:程序博客网 时间:2024/04/20 20:25
  1. A static variable inside a function keeps its value between invocations.
  2. A static global variable or a function is "seen" only in the file it's declared in

(1) is the more foreign topic if you're a newbie, so here's an example:

#include <stdio.h>void foo(){    int a = 10;    static int sa = 10;    a += 5;    sa += 5;    printf("a = %d, sa = %d\n", a, sa);}int main(){    int i;    for (i = 0; i < 10; ++i)        foo();}
In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.
原创粉丝点击