程序go 2009-02-21 06:47 采纳率: 100%
浏览 353
已采纳

"静态"在 c 中是什么意思?

I've seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?

转载于:https://stackoverflow.com/questions/572547/what-does-static-mean-in-c

  • 写回答

1条回答 默认 最新

  • Didn"t forge 2009-02-21 06:51
    关注
    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();
    }
    

    This prints:

    a = 15, sa = 15
    a = 15, sa = 20
    a = 15, sa = 25
    a = 15, sa = 30
    a = 15, sa = 35
    a = 15, sa = 40
    a = 15, sa = 45
    a = 15, sa = 50
    a = 15, sa = 55
    a = 15, sa = 60
    

    This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.

    (2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static, so that the user won't be able to access them. This is encapsulation, a good practice.

    Quoting Wikipedia:

    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.

    See here and here for more details.

    And to answer your second question, it's not like in C#.

    In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序