How the static keyword is used in C and C + +

Source: Internet
Author: User

The two methods of using the static keyword of the C language

1), for function interior modifier variables, that is, static variables inside the function. The lifetime of this variable is longer than the function, the function has a certain "state", functions that use static variables are generally non-reentrant, is not thread-safe, such as Strtok ()

2) Use at the file level (outside the function body), modify the variable or function, the variable or function can only be visible in the text, other files cannot be seen, and the variable or function cannot be accessed.

Four ways to use the static keyword for C + + language

Because C + + introduces class, there are two new uses for the static keyword while maintaining compatibility with the C language:

3), user decorated class data member, so-called "static member", the lifetime of this data member is greater than the object of Class (entity/instance), static data members are one copy of each class, ordinary data members are one copy of each iinstance, So it is called class variable and instance variable, respectively.

4), a member function for modifying class, the so-called "static member function", this member function can only access class variable or other static program functions, cannot access instance variable or instance method.


These usages can be combined, such as C + + 's member function (whether static or instance) can have its local static variables (the above usage 1). For class template and function template, the true number of static objects is related to template instantiation (templates are present).

How the static keyword is used in C and C + +

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.