• c中static变量局部变量


    来看看《c专家编程》中一段程序(略有变化):

    #include <stdio.h>
    void init(char *str)
    {
        
    static char s=' ';
        printf(
    "%c %s\n",s,str);
         s
    =',';
    }

    int main()
    {
        init(
    "hhh");
        init(
    "hhh");
        init(
    "hhh");
        
    return 0;
    }

     输出如下:

     

     c中的局部static变量只初始化一次。为了理解,来看看汇编代码:

    .data
        .type    s.
    0,@object
        .size    s.
    0,1
    s.
    0:
        .byte    
    32           #在这里初始化
        .section    .rodata
    .
    LC0:
        .string    
    "%c %s\n"
        .text
    .globl init
        .type    init,@function
    init:
        pushl    %ebp
        movl    %esp, %ebp
        subl    $
    8, %esp
        subl    $
    4, %esp
        pushl    
    8(%ebp)
        movsbl    s.
    0,%eax  #s->eax
        pushl    %eax
        pushl    $.LC0
        
    call    printf
        addl    $
    16, %esp
        movb    $
    44, s.0
        
    leave
        
    ret

     我们看到,在init内部并不存在为s初始化的语句,s位于数据区,且在init外部初始化。

  • 相关阅读:
    输入一批整数,输出最大最小值,输入0结束
    获取最低价手机价格
    插入数值
    猜数游戏
    数字金字塔
    输出星期数
    9*9乘法表
    linux 出core设置问题
    linux socket连接中 ERRNO错误
    linux c 获取头文件函数getenv
  • 原文地址:https://www.cnblogs.com/hustcat/p/1513755.html
Copyright © 2020-2023  润新知