Static variable local variable in c

Source: Internet
Author: User

Let's take a look at a program (slightly changed) in Expert c programming ):

# 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;
}

The output is as follows:

 

Local static variables in c are initialized only once. For understanding, let's look at the assembly code:

. Data
. Type s.0, @ object
. Size s.0, 1
S.0:
. Byte 32 # initialize here
. 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

We can see that there is no statement for s initialization in init. s is located in the Data zone and initialized outside init.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.