Use of static in C Language

Source: Internet
Author: User

During the development process, we often need to define some static variables or functions. Let's talk about static in detail;

1. Modify Variables

When static is used to modify a variable, the visible range and lifecycle of the variable are doomed;

(1) When modifying global variables

Static int flag1 = 0;

Int flag2 = 0;

These two variables are stored in the global data zone. flag1 is only visible in this file, but not in other files. flag2 can be used in other files by declaring extern int flag2;

(2) When modifying a local variable

Void fun (void ){

Static int temp1;

Int temp2 = 0;

......................

Return;

}

In the function, temp1 is a local static variable, stored in the global data zone, and temp2 is a local variable and stored on the stack. However, as the function exits, the lifecycle of temp2 ends, however, temp1 is still valid, and only the visible range is within this function. When you enter this function again, any modifications to temp1 are made based on the previous modification, that is, temp1 has a memory.

2. Modifier

Static modifiers are mainly functions used in this file and are not provided externally. static functions of this type are available in any file in the Linux kernel;

Static inline void enable_noirq (void ){

................

}

The advantage of using the static modifier is that all files can define functions with the same name, and compilation errors caused by duplicate names are not considered;

Related Article

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.