The role of the static keyword.

Source: Internet
Author: User

The role of the static keyword.

1. static modified variables will be stored in the memory until the end of the program is destroyed, no matter where you define the variable in the code. Therefore, the static variable you defined will only be initialized once, and the value of the static variable you obtained will be the value assigned last time.

Code:

1 void play () 2 {3 static int I = 0; // This will only be executed once 4 .. 5 I = 2; 6... 7}

When pla finishes its first call, I still exists in the memory and the value is 2. When this function is called for the second time and enters this function, the value of I is still 2; that is to say, I always exists in the memory.

2. Avoid conflicts caused by multiple developers using the same global variable name in multiple files.

* Add the static modifier before the same global variable in the respective files. In this way, the system will allocate different memory for them.

* Variables modified with static are only visible within the scope of the variable. This is the difference between it and global variables.

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.