This chapter mainly introduces several concepts
(1) variables and constants
Basic Types of variables: bool, Char, Int, short, long, float, and double. Pay attention to the number of bytes occupied by each variable.
Constant classification: Macro constants, const constants, and string constants. Note the differences between macro constants and cons constants.
# Define max 100 // macro constant
Const int max = 100; // const constant in C ++
Char * P = "Hello World"; // String constant
(2) global variables and static variables
Global variables: static storage with a global scope. You only need to define a global variable in one source file to apply it to all source files. Use the extern keyword to declare the global variable again.
Static variables: static storage, which are classified into static global variables and static local variables due to different scopes. Static global variables act on the source files defined by them, and cannot act on other source files. That is, variables modified by the static keyword have file scopes. Static local variables are only visible to the defined function bodies. That is, if a global variable is added with static, its scope can be changed without changing its memory storage location. If a local variable is added with static, its memory storage location will be changed without changing its scope.
Static variables are also introduced because the compiler allocates space for the variables defined inside the function when the program executes its definition, the space allocated by the function on the stack is released at the end of the function execution, which leads to a problem: If you want to save the value of this variable in the function to the next call, how to implement it? The easiest way to think of is to define a global variable, but defining a global variable has many disadvantages, the most obvious drawback is that the access range of the variable is broken (so that the variables defined in this function are not controlled by this function ).
A small test on static variables:
#include <iostream>
using namespace std;
int Test(int a)
{
static int b=5;
b+=a;
return b;
}
int main()
{
int a=Test(10);
cout<<a<<endl;
int b=Test(20);
cout<<b<<endl;
return 0;
}