Static in C/C ++

Source: Internet
Author: User
In C, static has two meanings:

(1) If the static int Foo; clause is in the function, static indicates the storage attribute, indicating that foo is a static variable. In the static storage area, only one space is occupied. Its lifecycle andProgramSame length.

(2) If the static int Foo; clause is located outside the function, foo is a global variable. Static does not represent the storage property, but is used as a delimiter: it is used to restrict the visible range of the global variable Foo and restrict its scope to the file where it is located. It is invisible to other files. Static void func (); indicates that the function is only visible in this file.

In C ++, the static member in the class indicates that all objects share the storage zone. Static member functions can only access static members. Static member initialization must be in the file range, even private members. Static member functions can be called using objects + member functions, or using classes + member functions.

// Example of the static keywordstatic int I; // variable accessible only from this filestatic void func (); // function accessible only from this fileint max_so_far (INT curr) {static int biggest; // variable whose value is retained // between each function call if (curr> biggest) biggest = curr; return biggest ;} // C ++ onlyclass savingsaccount {public: static void setinterest (float newvalue) // member function {currentrate = newvalue;} // that accesses // only static // membersprivate: char name [30]; float total; static float currentrate; // one copy of this Member is // shared among all instances // of savingsaccount }; // static data members must be initialized at File Scope, even // if private. float savingsaccount: currentrate = 0.00154;

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.