Notes, always updated
First, use Xcode or terminal to run C + + programs on Mac
The second chapter, Xcode basic Use tutorial
C + + Comments:
/* */
Data Type
When programming in a programming language, you need to use a variety of variables to store information. The variable retains the memory location of the value it stores. This means that when you create a variable, you reserve some space in memory. The operating system allocates memory based on the data type of the variable and determines what is stored in the reserved memory.
C + + variable scope
A scope is an area of a program, and in general there are three places where variables can be defined:
-A variable declared inside a function or a block of code, called a local variable.
-A variable declared in the definition of a function parameter, called a formal parameter.
-A variable declared outside all functions, called a global variable. Integer Constants
Integer constants can be decimal, octal, or hexadecimal constants. prefix specifies cardinality: 0x or 0X is hexadecimal, 0 is octal, and decimal is by default without a prefix.
Integer constants can also take a suffix, which is a combination of u and L, u represents an unsigned integer (unsigned), and L represents a long integer. Suffixes can be uppercase or lowercase, and the order of U and L is arbitrary.
To Define constants:
In C + +, there are two simple ways to define constants:
Using #define preprocessor.
Use the const keyword.
As shown in figure:
Note that it is a good programming practice to define constants as uppercase letters.
C + + storage class
the storage class defines the scope (visibility) and lifecycle of a variable/function in a C + + program. These specifiers are placed before the type they are decorated with. The storage classes available in C + + programs are listed below:
Auto
Register
Static
extern
mutable
Thread_local (C++11)
Starting with C + + 11, the Auto keyword is no longer a C + + storage class descriptor, and the Register keyword is deprecated. Auto Storage class
Since C + + 11, the Auto keyword is used in two cases: the type of the variable is automatically inferred based on the initialization expression when the variable is declared, and the placeholder for the return value of the function when the function is declared.
Register Storage Class
The Register storage class is used to define local variables that are stored in registers rather than in RAM . This means that the maximum size of a variable is equal to the size of the register (usually a word) and cannot be applied to a unary ' & ' operator (because it has no memory location). registers are used only for variables that require quick access, such as counters. It should also be noted that the definition of ' register ' does not mean that the variable will be stored in the register, it means that the variable may be stored in the register, depending on the hardware and implementation constraints.
{
Register int miles;
}
Static Storage class
The static storage class instructs the compiler to maintain the existence of local variables within the lifetime of the program without needing to create and destroy each time it enters and leaves the scope. Therefore, you can use static to modify local variables to preserve the values of local variables between function calls. extern storage class
The extern storage class is used to provide a reference to a global variable that is visible to all program files. When you use ' extern ', the variable name is pointed to a previously defined storage location for variables that cannot be initialized.
When you have multiple files and you define a global variable or function that you can use in other files, you can use extern in other files to get a reference to a variable or function that you have defined. As you can understand, extern is used to declare a global variable or function in another file.
An extern modifier is typically used when two or more files share the same global variable or function, as follows:
First file: main.cpp
#include <iostream>
int count;
extern void Write_extern ();
int main ()
{
count = 5;
Write_extern ();
}
Second file: Support.cpp
#include <iostream>
extern int count;
void Write_extern (void)
{
std::cout << ' Count is ' << count << Std::endl;
}
& Address
* Take the address of the corresponding data
#include <iostream>
using namespace std;
#define LENGTH
int main (int argc, const char * argv[]) {
//Insert code here ...
int a = 6;
int *ptr;
ptr = &a;
cout << *ptr << Endl;
}
Key points:
cout only the pointer to a char array, the contents of the address it is pointing to, other types of pointers that do not intelligently judge, but rather output only the address of the pointer, not the content
Loops
while (condition)
{
statement (s);
}
for (init; condition; increment)
{
statement (s);
}
A For statement allows a simple range iteration: (as in python for similar)
int my_array[5] = {1, 2, 3, 4, 5};
Each array element is multiplied by 2 for
(int &x:my_array)
{
x *= 2;
cout << x << endl;
}
The auto type is also c++11 the new standard, the type for automatically getting the variable for
(auto &x:my_array) {
x *= 2;
cout << x << endl;
}
Do
{
statement (s);
} while (condition);
Infinite loop
for (;;) {} to judge
if (boolean_expression)
{
//If Boolean expression is true the statement to be executed
}
if (boolean_expression)
{//
if the Boolean expression is true the statement to be executed
}
else
{
//If the Boolean expression is the statement that will be executed
}
if (boolean_expression 1)
{
//If the Boolean expression 1 is True, execute
}
else if (boolean_expression 2)
{
// Executes if the Boolean expression 2 is True
(boolean_expression 3)
{
//If Boolean expression 3 is True
}
else
{
/ /execute when none of the above conditions are true
switch (expression) {case
constant-expression :
statement (s);
Break Optional case
constant-expression :
statement (s);
Break Optional
//You can have any number of case statements
default://optional
statement (s);
}
function
In C + +, a function consists of a function header and a function body. The following lists all the components of a function:
return type: A function can return a value. Return_type is the data type of the value returned by the function. Some functions perform the desired action without returning a value, in which case return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the argument list together form the functional signature.
Parameters: parameters are like placeholders. When a function is called, you pass a value to the parameter, which is called the actual argument. The parameter list includes the type, order, and quantity of the function arguments. parameter is optional, that is, the function may not contain parameters.
Function Principal: A function body contains a set of statements that define functions to perform tasks.
Link: http://www.runoob.com/cplusplus/cpp-functions.html
Parameters can be with default values, just like Python
Some calculation functions:
Generate random Number:
Array
C + + supports an array data structure that can store an ordered set of elements of the same type of fixed size . An array is used to store a series of data, but it is often considered a series of variables of the same type.
all arrays are made up of contiguous memory locations . The lowest address corresponds to the first element, and the highest address corresponds to the last element.
The array name can be used as a pointer to the first element of the array:
cout << myarray1 << Endl;
The above code outputs the address of the first element of the array. 0x7fff5fbff6b0
If you use an indirect value operator.
cout << *myarray1 << Endl;
It will output the value of this address.
Or
cout << * (Myarray1 + 3) << Endl;
Will remove the value of myarray1[4]
C + + passes an array to a function, the array type is automatically converted to the pointer type, and thus the actual address is transmitted.
If a function needs to receive an array as an argument, there are three ways to declare it:
void MyFunction (int *param) {}
void MyFunction (int param[10]) {}
void MyFunction (int param[]) {}
All three of these forms indicate that the parameters here require a pointer, so it is possible to pass the array name when passing the value.
It says that the array is passed as a parameter to the function. Next
What to do if a function returns an array.
Look directly at the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
function
int * GETRANDOM ()
{
static int r[10]
to generate and return random numbers; Sets the seed
Srand ((unsigned) time (NULL));
for (int i = 0; i < ++i)
{
R[i] = rand ();
cout << R[i] << Endl;
}
return r;
}
To invoke the main function
int main () {//) that defines the function above,
a pointer int *p that points to an integer
;
p = getrandom ();
for (int i = 0; i < i++)
{
cout << "* (P +" << I << "):";
cout << * (P + i) << Endl;
}
return 0;
}
You can see two points: 1. Cannot return the entire array, still returns the array name, which is the pointer to the first element.
2. The array created in the function needs to be static. A personal understanding is that a variable within a function is a local variable that disappears as the function ends. But the function returns not a reference, but a pointer. If this local variable disappears, the returned value cannot find the address again. So you need a static string
The string is actually an array of one-dimensional characters terminated with the null character ' ".
Two kinds of C language methods:
Char greeting[6] = {' H ', ' e ', ' l ', ' l ', ' o ', ' n '};
Char greeting[] = "Hello";
Some functions:
The following C + + provides a string class that is more intuitive:
String str1 = "Hello";
String str2 = "World";
string Str3;
STR3 = str1;
cout << str3 << Endl;
cout << str1 + str2 << Endl;
Output:
Hello
Helloworld
#include <iostream>
#include <string>
using namespace std;
int main ()
{
//define a String object
string http = "Www.runoob.com";
Print string length
cout<
Pointers
A pointer is a variable whose value is the address of another variable, that is, the direct address of the memory location. Just like other variables or constants, you must declare them before using the pointer to store the other variable addresses. The general form of a pointer variable declaration is:
Type *var-name;
Here with the asterisk, is to define this as a pointer. And when using this pointer, this pointer is var-name.
And *var-name represents the value of the position that the pointer points to.
Example:
#include <iostream>
using namespace std;
int main ()
{
int var =; The declaration of the actual variable
int *ip; Declaration of pointer variable
IP = &var; Store the address of Var in a pointer variable
cout << "Value of var variable:";
cout << var << endl;
The output is stored in the pointer variable
cout << "address stored in IP variable:";
cout << IP << endl;
To access the value of the address in the pointer
cout << "value of *IP variable:";
cout << *ip << Endl;
return 0;
}
when a variable is declared, it is a good programming practice to assign a NULL value to a pointer variable if there is no exact address to assign.
int *ptr = NULL;
You can write this:
The current pointer is compared to the position of the last data in the array, if it is less than, the following code is added:
while (PTR <= &var[max-1])
{
cout << "Address of var[" << i << "] =";
cout << ptr << Endl;
cout << "Value of var[" << i << "] =";
cout << *ptr << Endl;
Point to previous position
ptr++;
i++;
}
Array of pointers: At this point we need an array with pointers stored inside:
int *ptr[max]
Here, the PTR is declared as an array, consisting of the MAX integer pointer. Therefore, each element in PTR is a pointer to an int value.
Explanation: If int Ptr[max], it is assumed that the value of MAX int type is stored in PTR
When the int type becomes an int *, it is assumed that the max pointer to int data is stored in PTR.
C + + pointer to pointer (multilevel indirection)
A pointer to a pointer is a form of multi-level indirection, or a pointer chain. Typically, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, and the second pointer points to the position that contains the actual value.
A pointer variable that points to a pointer must be declared as follows, placing two asterisks before the variable name. For example, the following declares a pointer to an int type pointer:
int **var;
int var = ten;
int *ptr = NULL;
int **pptr = NULL;
ptr = &var;
Pptr = &ptr;
cout << **pptr << Endl;
Remember: If the function returns a pointer, the pointer must not point to the address of the local variable, use static. Reference
int i =;
int& r = i;
double& s = d;
To put it bluntly, you use the type& syntax to give a previous variable a name .
That is, the variable has two names, one is the original variable name, the other is a reference.
The reference and variable name are consistent in usage.
A reference variable is an alias, that is, it is another name for an existing variable. Once you have initialized a reference to a variable, you can use that reference name or variable name to point to the variable.
Since a reference is an alias for a variable, why do you need to refer to it?
references are typically used for function argument lists and function return values
·
C + + to increase the reference type, mainly as a function parameter, to expand the function of the function of passing data.
C + + Function reference:
(1) The variable masterpiece is the actual parameter and the formal parameter. The value of the variable is passed to the parameter, and the pass is one-way. If the value of the formal parameter changes during the execution of the function, it is not returned to the argument. Because the formal parameter and the argument are not the same storage unit when the function is invoked.
(2) A pointer to a variable is passed. The parameter is a pointer variable, the argument is the address of a variable, and when the function is called, the formal parameter (pointer variable) points to the real parametric unit. This can change the value of an argument by using a parameter pointer.
(3) C + + provides a reference for passing variables. A formal parameter is a reference variable, and an argument is a variable, and when a function is invoked, the formal parameter (reference variable) points to the real parametric unit. This can change the value of an argument through a parameter reference.
void swap (int& x, int& y)
{
int temp;
temp = x; /* Save the value of address x
/x = y; /* Assign y to x */
y = temp;//* assign X to Y/return
;
}
As you can see, using references, swapping the values of x and y within a function, is really changing the value of x, y in memory, with the same effect as the pointer.
Replacing pointers by using references makes C + + programs easier to read and maintain.
.
A C + + function can return a reference similar to returning a pointer.
When the function returns a reference, it returns an implicit pointer to the return value. This allows the function to be placed on the left side of the assignment statement.
On this issue, I was only given a warning during the coding process, and no error was reported.
Time, Date
The C + + standard library does not provide the so-called date type. C + + inherits the structure and functions of the language for date and time operations. In order to use date and time related functions and structures, you need to refer to the <ctime> header file in your C + + program.
RELATED LINKS
The TM structure is especially important when dealing with date and time related operations in C + + .
The TM structure specifically includes what to see above the link. Input and Output
This is the most basic and most common I/O operation in C + + programming. More versatile follow-up introduction.
I/O in C + + occurs in the stream, which is a sequence of bytes .
Standard input stream (CIN)
Standard error Stream (CERR):
The predefined object Cerr is an instance of the Iostream class. The Cerr object is attached to a standard error device, usually the display, but the Cerr object is not buffered, and each stream is immediately exported when inserted into Cerr.
Standard log Stream (clog):
The predefined object clog is an instance of the Iostream class. The clog object is attached to the standard error device and is usually the display, but the clog object is buffered. This means that each stream inserted into the clog will be stored in the buffer until the buffer fills up or the buffer is refreshed.
The bold part is the difference between clog and cerr.
Good programming practices tell us to use the Cerr stream to display error messages, while other log messages use the clog stream for output. structure
In order to define the structure, you must use the struct statement. The struct statement defines a new data type that contains more than one member, and the struct statement is in the following format: Declare a struct type books, and the variable is book:
struct book{
char bookname[50];
Char authername[50];
Char subject[50];
int bookid;
} Book
To access struct Members:
struct book{
char bookname[50];
Char authername[50];
Char subject[50];
int bookid;
};
Book Book1;
strcpy (Book1.bookname, "go");
strcpy (book1.authername, "xxx");