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外部初始化。

posted @ 2009-06-30 10:32  YY哥  阅读(1558)  评论(2编辑  收藏  举报