C++ Basics_Day01

Preparation tools Vscode or Clion or Dev C++ or Vs studio and
MSYS2 are important cross-platform tool chains for C++.

Preparation

Install MSYS2

Insert image description here
Insert image description here
Insert image description here
pacman -S mingw-w64-ucrt-x86_64-gccAfter Y

Finally use cmdgcc --version

Insert image description here
Add environment variables:
Insert image description here

software

CLion

Create a file

Right-click–New–C/C++ Source File
Insert image description here
Insert image description here

1. Basic introduction

1.1C++ source files

The file usually ends with the .cpp or .cxx suffix.

#include<iostream>
using namespace std;
// main有且仅有一个
int main() {
    
    

	cout << "Hello C++__world" << endl;
	//system("pause");
	return 0;
}

Insert image description here
The main function contains only one line of code: this single statement begins with std and ends with a semicolon (;)
.

1.2 Code comments

A comment is a special statement used to explain the function and purpose of the program when writing code. The compiler will automatically detect and ignore it. Comments do not have any impact on the function of the program.

Format:
(1) Single-line comment: // 后接对代码的描述
It is better to place it above the code, or at the end of the code statement.

(2) Multi-line comments: /*多行注释*/
Since the code may be longer, it is recommended to write it at the top of the whole.

1.3 Variables and Constants

1.3.1 Variables

给一段指定的内存空间起名,方便操作这段内存

Syntax :数据类型 变量名 = 初始值;

Note : It is best to assign an initial value to the variable when defining it. Because the variable operates on the specified memory space, when defining the variable, a certain space will be found, but there is no guarantee that the original value of the modified space will not be available.

#include<iostream>
using namespace std;

int main() {
    
    
	//最好是在定义的时候,给变量赋初值。
	int a = 5;
	//带有中文输出的内容,需要把编码格式改为GBK
	cout << "a 的值= " << a << endl;
	
	system("pause");

	return 0;
}

1.3.2 Constants

不随任何的行为而改变自身数据

Syntax :
(1) #define macro definition #define 常量名 常量值
is defined above the source file

(2) A variable modified by const. const 数据类型 常量名 = 常量值
The variable modified by const is a constant and cannot be modified.

1.3.3 The difference between the two:

Although both methods can be used to define constants, there are still some differences:

  1. #define macro constants :

    • Use preprocessing directives, simple replacement, no type checking.
    • Does not occupy memory and is directly replaced by a constant value (it is a simple text replacement, which replaces symbols with corresponding text;That is: the constant defined by #define has no storage space allocated and no corresponding address.)。
    • You can define functions, expressions, etc., not just constants (define can use expressions as names).
    • Macros are not restricted by scope and are available globally.
  2. const modified variables :

    • It is a real variable with a data type and will occupy memory. (Because the constant defined by const has storage space allocated in the memory, its address can be obtained
    • Providing type safety, the compiler will perform type checking.
    • There are scope restrictions and follow the scope rules of ordinary variables.
    • More recommended because it has type information and is easier to maintain and debug.

Generally, it is recommended to use const modified variables to define constants because it is more type safe and readable.

1.4 Keywords and identifiers

Keywords in C++ refer to reserved words with special meanings, such as "int" and "if"

在给变量或者常量起名称时候,不要用C++得关键字,否则会产生歧义。

Insert image description here

Identifiers are names defined by the programmer for naming variables, functions, etc. When naming identifiers, strive to achieve the effect of knowing the meaning by seeing the name, making it easier for you and others to read.

  • Identifier cannot be a keyword
  • Identifiers can only consist of letters, numbers, and underscores
  • The first character must be a letter or underscore
  • Letters in identifiers are case-sensitive

2. Data type

Data types in C++ can be divided into
Okay, I will continue to introduce the common basic data types and user-defined data types in C++.

2.1 Basic data types:

检验类型大小 ` sizeof(数据类型、变量) `

C++ is a statically typed language, which means that the data type of a variable or constant must be explicitly specified when it is created. The compiler needs to determine the data type of each variable at compile time in order to correctly allocate memory and perform appropriate operations.

Without specifying a data type, the compiler will not be able to correctly handle memory allocation and manipulation of variables, so the data type must be explicitly defined.

2.1.1 Integer type:

用于表示整数类型的数据,可以是正数、负数或零。区别在于存储的空间大小不同 

short < int <= long <= long long

short: 2 bytes - 2^15 - 2^15 -1
int: 4 bytes - 2^31 - 2^31 -1
long: usually 4 bytes on 32-bit systems, usually 8 words on 64-bit systems section, -2^31 - 2 ^31 -1
long long: 8 bytes -2^15 - 2 ^63 -1

2.1.2 Floating point type (real number):

用于表示带有小数的数值,其中`float`表示单精度浮点数,而`double`表示双精度浮点数。
  1. float:

    • floatIs a single-precision floating-point data type that typically occupies 4 bytes (32 bits) and can store approximately 7 significant digits.
    • Use fthe suffix to explicitly specify a floating point number as floattype, 3.14fe.g.
  2. double:

    • doubleIs a double-precision floating-point data type that typically occupies 8 bytes (64 bits) and can store approximately 15-16 significant digits.
  3. Scientific notation :

    • C++ supports scientific notation to represent floating-point numbers, using aeba notation of the form , where ais the coefficient, eis the exponent with base 10, and bis the sign of the exponent. For example, 3e2it represents (3 *10^2), which is 300; 0.03it can be written to 3e-2represent (3 *10^(-2)).

Example:

float pi = 3.14f; // 使用 f 后缀指定 float 类型
double largeNumber = 1.234567890123456789; // 默认为 double 类型

float a = 3e2; // 表示 300
float b = 3e-2; // 表示 0.03

2.1.3 Character type (char 1 byte):

Function : Used to represent a single character, based on ASCII code 1 .

grammar: char ch = 'a';

Note :
(1) Use single quotes to enclose characters. Example: char myChar = 'A';
(2) Single quotes can only contain one character, not a string. Example: char myChar = 'AB';It is not allowed. It should be char myChar = 'A';
(3) Character variable (char) in Usually 1 byte (8 bits) is used in C and C++, whether used to store the character itself or the corresponding ASCII code.

2.1.3. (1) Escape characters

used to express someASCII characters that cannot be displayed

Escape characters are added with a backslash (\) in front of a character to represent some special characters or operations. They are usually used to insert characters that are difficult to input directly into strings or character constants.

Commonly used escape characters are: \n \\ \t

2.1.4 Boolean type (bool):

The Boolean type (bool) is a data type used to represent true or false, occupying 1 byte in size in C++. It is the basic type used to make logical judgments.

bool flag = true;
	cout << flag << endl; // 1

	flag = false;
	cout << flag << endl; // 0

	cout << "size of bool = " << sizeof(bool) << endl; //1

2. 2 User-defined data types (subsequent):

  • Structure (struct) : Allows you to create a combination of multiple different data types. You can define multiple variables through the structure to describe the properties of an entity.
  • Class : allows the creation of custom data types with member variables and member functions, implementing the concepts of object-oriented programming, including encapsulation, inheritance, and polymorphism.
  • Enumeration type (enum) : allows the creation of a new data type containing a set of named constants.
  • Union : Union allows different data types to be stored in the same memory location. This means that members of a union share memory, and modifications to one member will affect other members.
  • Types defined by typedef : typedef is used to define new names for existing types to improve the readability and maintainability of the code.

2.3 String type

In C++, string types can be of two types: ordinary types and user-defined types, depending on the string representation used.

  1. Ordinary type (continues C language style):

    • In C++, strings can be represented using char arrays or pointers to characters. This method belongs to ordinary types and has no specific user-defined types. They are the basic string representation methods of C and C++.
    char str1[] = "Hello, world!";  // 字符数组表示字符串
    char* str2 = "Hello, world!";    // 字针表示字符串
    
  2. User-defined types :

    • On the other hand, C++ also provides std::stringthe class in the standard library, which is a user-defined string type. std::stringIt is a class that provides rich string operation functions and convenient string management.
    #include <string>
    
    std::string str = "Hello, world!";  // 使用 std::string 类型
    

std::stringIt is part of the C++ standard library. It provides many convenient string processing methods, such as string splicing, search, replacement and other operations, making string processing more convenient and efficient.

Therefore, a string can be a normal type (character array or pointer) or a user-defined type ( std::string), depending on how you choose to represent the string. If you need more information or have additional questions, please feel free to ask.

2.4 Data entry

Function: Used to obtain data from the keyboard

Keywords: cin

grammar: cin >> 变量

cinTypically used with operators >>to store input data into a specified variable. This makes it easy to receive input from the user and process it in the program

int x = 0;
	cout << "请输入整型变量x的值:" << endl;
	cin >> x;
	cout << x << endl;

3. Operators

Insert image description here
Note (1) Modulo operation cannot be performed on two decimals. The result is shown on the left.

	int a3 = 10;
	int b3 = 0;
	//报错,除数不可以为0
	//cout << a3 / b3 << endl; 
 
  // 两个小数不可做取模运算,结果看左边
  //  除数不为0
  cout << -10 % 3 << endl; //-1
  cout << 10 % 3 << endl;  // 1

//两个小数可以相除
	double d1 = 0.5;
	double d2 = 0.25;
	cout << d1 / d2 << endl;

(2) The assignment is '=', which is equal to '=='

Arithmetic operators
Insert image description here
Assignment operators
Insert image description here
Comparison operators
Insert image description here

Logical Operators
Insert image description here


  1. ASCII (American Standard Code for Information Interchange) encoding maps each character to a unique integer. For example, the ASCII code for the letter 'a' is 97. Therefore, when you create a character variable in C or C++, you actually store the ASCII code corresponding to the character in memory. ↩︎

Guess you like

Origin blog.csdn.net/m0_74154295/article/details/133436910