C + + key words static,const,volatile detailed

Source: Internet
Author: User
Tags constant modifier volatile

Static
static modifier local variable
The static modifier local variable is used to modify the storage location of the variable, from the automatic variable to the static variable (open space in the static area, not on the stack), but the link property and scope of the variable are unaffected. When static modifies a local variable, the variable is created before the program executes and exists throughout the execution space of the program, even if the scope is only hidden and does not destroy the variable. Take a look at the following two pieces of code


Code one: a local variable with no static modification

int main ()
{
int i=0;
for (i=0;i<10;i++)
{
int j=10;
J+=1;
printf ("%d", j); A J with no static modifier is 10 every time.
}
System ("pause");
return 0;
}



Code two: Static-decorated local variables

int main ()
{
int i=0;
for (i=0;i<10;i++)
{
static int j=10;
J+=1;
printf ("%d", j); J with a static modifier is a value after +1 last time.
}
System ("pause");
return 0;
}


From the above two pieces of code can see that the static modified local variable does change the location of the variable, stored in the static area, out of the scope has not been destroyed, so code two of J every time plus 1 after the value
Static cosmetic global variables and functions
Static modifiers and global variables are used to modify the link properties of the variable, changed from extern to internal, but the storage type and scope of the variable are unaffected, and the static-decorated global variables can only be accessed in their source files, even if external files use extern
Okay, here's the basic introduction to static, let's take a look at a static example.

int count=3;
int main ()
{
int i=0,sum=0,count=2;
for (i=0,sum=0;i<count;i+=2,count++)
{
static int count=4;
count++;
if (i%2 = 0)
{
extern int count;
count++;
Sum+=count;
}
Sum+=count;
}
printf ("%d%d\n", count,sum); 4 20
System ("pause");
return 0;
}

Is it a little dizzy to see this problem? I felt a little scared at first, too. Because there are three different ways of storing variables count: Global, local, static, and the key is that it also uses count of times at a time. It's easy to figure out which count to call in each use, but don't be afraid, Let's analyze it slowly.



Attention:
1. When authorities and global variables collide, local variables take precedence, and local variable count is preferred when global count and local count appear simultaneously
2. extern declares a variable to have an external link property
3. Static modifier local variable (does not destroy the variable out of scope is hidden)
Const
Why Mulao have the const keyword? And what Mulao can the const modify? What is Mulao different from the const modifier? These three issues are mainly discussed below.
To solve the first problem, you need to understand the macros and identifiers defined by define, see links below for details

After a general understanding of the identity Fu Haihong defined by define, we will find many disadvantages of macros defined by define: macros cannot be debugged, macros are replaced directly, and when more is replaced, space is wasted; macros can be typed but the macros themselves are of no type; macros have side effects; And these shortcomings can be solved by the Const. As you can see from the following code

#define The identifier defined by MAX 5//define
const int MAX=10//is not put Max in memory at this time but is placed in the symbol table
int main ()
{
int I=max; Substitution of identifiers during precompilation
int J=max; The memory is allocated for J at this time and is no longer allocated
int M=max; Replace the macro again, then allocate the memory
int N=max; No more separate memory matches

Because the compiler usually does not allocate storage space for ordinary const read-only variables, it saves them in a symbol table, which makes the variable a value during compilation, and has no operation to store and read memory, making it more efficient. This solves why Mulao in C + + instead of define defined identifiers and macros.
const modifier Variable
Const modifies a variable when the const can be on the left side of the type or on the right side of the type, such as

const int a=10;
int const A=10;

In C, a const modifier variable makes the variable permanent but remains a variable (the const-modified variable in C is an ordinary variable)
But in C + + to eliminate the disadvantages of macros and also need to define constants, the const-modified variable removes its attribute from the variable in C and completely upgrades it to a constant amount (a const-modified variable in C + + is constants) such as the following code:

const int a=10;
int arr[a]={0};

The length of an array must be a value that represents a constant, and if it can be run under. cpp, it is possible to explain whether the const-modified variable in C + + is true; The above code is not operational in the. c file, and it can be run under. CPP, which shows that The const modifier of a variable already has no property of a variable, and is completely a constant
Const modifier pointer
const modifier level pointer
1). Const on the left of *

int a=10;
int b=20;
const INT *pa=&a;
*pa=20; Error
a=20;
pa=&b;

The const modifier is *PA, which means that the content pointed to by the pointer PA can not be modified, but can also change the pointer variable itself by modifying the variable that the PA pointer points to.
2). Const on the right side of the *

int a=10;
int b=20;
int *const pa=&a;
pa=&b;//(Error)
*pa=b;

The const modifier is a PA, stating that the pointer variable itself cannot be modified, but can modify what the pointer points to;
3). The const is on the left of the * and on the right side of the *

int a=10;
int b=20;
const INT *const pa=&a;
pa=&b;//(Error)
*pa=b;//(Error)

At this point, the const is modified *PA also modifies the PA, indicating that the pointer to the content can not be modified, the pointer variable itself can not be modified
Tips for helping your memory:
If we think of PA and a as relationships between men and women, girl A can change her boyfriend. As the address of the variable itself can be modified, girl A can spend a boyfriend's money similar to the contents of the variable can be modified; The const on the left of the * is like this girl A is a man who can change her boyfriend but can't spend her boyfriend's money, const On the right side is like this girl A is can spend boyfriend money but can not change a boyfriend, const if that is on the left side of the * on the right that this girl can be miserable, that is, can not change boyfriends can not spend money, is it interesting?
const modifier Level Two pointer
1). Const on the left of the first *

int a=10;
int b=20;
int *pa=&a;
int *pb=&b;
const INT **ppa=&pa;
**ppa=b;//(Error)
ppa=&pb;
*ppa=&b;
a=40;

The point relationship is the following figure:


          
            const modifier On the left side of the first *, remove the type we found that it modifies the **PA, which means that we are not allowed to modify the value of a by a two-level pointer PPA to the space of a, but we can change the contents of the space by a , you can also modify the PPA pointer variable itself
         2). Const in the middle of two *
            
 int a=10
 int b=20;
 int *pa=&a;
 int *pb=&b;
 int *const *ppa=&pa;
 ppa=&pb;
 *ppa=&b;//(Error)
 **ppa=b

           Const modifier in the middle of two *, according to the nearest principle, we know that the Const modifier is *ppa, This means that at this point we cannot change the contents of the space PA that the PPA points to, but we can modify the PPA pointer variable itself, or modify the value of the two-level pointer PPA pointing to space A,
       3). The const is placed on the right side of the second *
        
 int a=10
 int b=20;
 int *pa=&a;
 int *pb=&b;
 int **const ppa=&pa;
 ppa=&pb;  //(Error)
 *ppa=&b
 **ppa=b

The const is placed on the right side of the second *, and according to the nearest principle, we know that the Const modifier is a PPA, which means that at this point we are not allowed to modify the address of the two-level pointer, the PPA pointer variable itself
There are many situations in the Const modifier two-level pointer, which only discuss a two-level pointer with a const modifier, so just grasp the point and clearly what Mulao is the const modifier? Second-level pointer itself? What does a secondary pointer point to the contents of a first-level pointer? A secondary pointer to the address of a primary pointer? The second level pointer indirectly points to the contents of the variable? As long as the clarity of these can be very good control of the const modifier pointer problem.
Const modifier Reference
1. A const modifier refers to the alias of a variable that does not have permission to modify the contents of the variable, only through which the variable is modified

int a=10;
const INT &refa=a;
refa=20; Error
a=20;


2. The permissions of the const modifier variable can be narrowed but cannot be extended

const int a=10;
int &refa=a; Error
int b=20;
const INT &refb=b;

3. Const modifies a global variable, which is stored in a read-only data area, and cannot be modified even with a pointer, which is not necessarily allocated when the space is used.

const int n=10; Const COSMETIC global variable
int main ()
{

int arr[n]; As long as it is stated that n is a constant and unallocated space
const INT *p=&n; It's time to allocate space for n
System ("pause");
return 0;
}


Assigns the address of a const-decorated global variable to the pointer, which is used.



4. Constants have constancy, only constant references can refer to constants

int &refa=5; Error
const INT &refb=5;

5). Reference types do not match

Double d1=3.1;
const INT &refd1=d1; 3
d1=6.95;
Attention:
1. When allocating space in memory for a variable, there is a temporary variable, and the temporary variable is persistent (the default type is const int)
2. When the name of the variable itself and the type of alias does not match, the reference is not D1, but this temporary variable
3. Since it is a temporary variable will be destroyed after use, so when you modify the value of the variable D1 will not affect the value of REFD1


6. The parameters of the const modifier function, the return value of the modifier function:


You can add a const modifier to a function's arguments when you want to not be able to modify the value of the variable within the function.
Const can also modify the return value of a function, the return value of the function cannot be modified at this time, or the return value of the const modifier can be used when it is really necessary to return a constant value, such as the copy constructor of the six default member functions of the class that is a literal reference, and a copy constructor with a date class as an example

Date (const date& D)
: _year (D._year)
, _month (D._month)
, _day (D._day)
{}


Const modifier member function
The const modifier member function, which is appended to the member function, const,const the object that the this pointer points to, ensuring that the object that calls the member function is not changed within the function

To observe the specific transfer process of the Const modified member function with the example of date class



Date class

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace Std;

Class Date
{
Public
Date (int year,int month,int Day)
: _year (year)
, _month (month)
, _day (Day)
{}
void Display () const
{
cout<<_year<< "-" <<_month<< "-" <<_day<<endl;
}
void Display ()
{
cout<<_year<< "-" <<_month<< "-" <<_day<<endl;
}
Private
int _year;
int _month;
int _day;
};
int main ()
{
Date D1 (2016,8,10);
D1. Display ();

Const Date D2 (D1);
D2. Display ();
System ("pause");
return 0;
}


Here are a few questions, which are the permissions of the const modifier variable that we mentioned earlier (permissions can be narrowed but not extended)
1. A const object cannot call a non-const member function, you can call the const member function
2. A non-const object can call a member function that is not a const, or it can call a const member function
3. The const member function can invoke other const member functions, and no const member functions can be invoked
4. You can call other member functions within a non-const member function, or you can call a non-const member function

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.