Skip to content

Wiki

C++Basic Introduction

About 19 min read

Existing English translations were reused. 12 current source blocks remain in Simplified Chinese, without triggering paid translation.

1.C++First acquaintance

1.1.Operating Conventions for This Chapter

本章的代码示例默认在 C++开发环境搭建与测试 下载并跑通的 CMake 模板中运行。

Starting from this chapter, for the preliminary grammar exercises, only modify this file:

src/main.cpp

For each example, you can copy the code into src/main.cpp and then rebuild and run the template program.

For now, do not modify these files and directories:

  1. CMakeLists.txt
  2. src/CMakeLists.txt
  3. src/lib1/
  4. src/lib2/

There is also no need to manually write g++ main.cpp. We will continue to use the CMake template that was already working in the previous chapter to compile the program.

Common commands:

Linux:

cmake --build --preset linux-debug
./build/linux-debug/src/cmake_template

Windows,PowerShell:

cmake --build --preset windows-debug
./build/windows-debug/bin/cmake_template.exe

If you have not yet completed the engineering environment setup from the previous chapter, please first see the section starting from C++Development Environment and the First Project; this tutorial has consistently used the same CMake template. At this point, your project should still roughly have this structure.

1.2.The firstC++program

Open the following in the project:

src/main.cpp

Replace the content with:

#include <iostream>

using namespace std;

int main()
{
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。
	cout << "Hello world" << endl;

	// 返回 0 表示程序正常结束。
	return 0;
}

Operation result:

Hello world

1.2.1.Build and run the program

Execute in the project root directory: (or directly use the graphical interface compilation discussed in the previous section, and below I will also teach you again)

Linux:

cmake --build --preset linux-debug
./build/linux-debug/src/cmake_template

Windows,PowerShell:

cmake --build --preset windows-debug
./build/windows-debug/bin/cmake_template.exe

Graphical steps:

Configured in build+debug mode:

alt text

Click build in the lower left corner.

alt text

Run

alt text

alt text

Terminal output:

Hello world

1.3.main function parameters

main Functions do not have to take parameters. The two most common forms are:

int main()
{
	// 程序从 main 函数开始执行,下面的语句会按顺序运行。
	// 返回 0 表示程序正常结束。
	return 0;
}

Run result: The program ended normally, with no output in the terminal.

int main(int argc, char* argv[])
{
	// 程序从 main 函数开始执行,argc/argv 用来接收命令行参数。
	// 返回 0 表示程序正常结束。
	return 0;
}

Run result: The program ended normally, with no output in the terminal.

Among them:

  • argc Indicates the number of command-line arguments, usually at least 1, because the path of the program itself is also counted as an argument.
  • argv Indicates the array of command-line arguments,argv[0] is usually the path or name of the program itself,argv[1] Only then do the arguments passed in by the user begin.
  • char* argv[] It can also be written as char** argv; here both express the same meaning.

Example:

#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    // 程序从 main 函数开始执行,argc/argv 用来接收命令行参数。

	cout << "argc = " << argc << endl;

	for (int i = 0; i < argc; i++) {
		cout << "argv[" << i << "] = " << argv[i] << endl;
	}

	// 返回 0 表示程序正常结束。
	return 0;
}

Run result:see "Run result" below;argv[0] will vary with the startup method. Focus on the correspondence between argc and each argv.

Build and pass command-line arguments to run:

Linux:

cmake --build --preset linux-debug
./build/linux-debug/src/cmake_template hello 123

Windows,PowerShell:

cmake --build --preset windows-debug
./build/windows-debug/bin/cmake_template.exe hello 123

Running result:

argc = 3
argv[0] = ./build/linux-debug/src/cmake_template
argv[1] = hello
argv[2] = 123

注意:上面按 Linux 的运行路径展示结果。Windows 中程序路径通常包含 windows-debug/bin/cmake_template.exe,这属于正常的平台差异。argv[0] 的具体内容和启动方式有关,可能是 ./build/linux-debug/src/cmake_template,也可能是完整路径。实际处理参数时,通常从 argv[1] 开始读取用户输入的内容。

1.4.Comment

作用:在代码中加一些说明和解释,方便自己或其他程序员程序员阅读代码

Two formats

  1. Single-line comment:// 描述信息
    • Usually placed above a line of code, or at the end of a statement, ==to explain that line of code==
  2. Multi-line comment: /* 描述信息 */
    • Usually placed above a block of code, ==to provide an overall explanation of that block of code==

Tip: When compiling code, the compiler ignores the content of comments.

1.5.Variable

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

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

Example:

#include<iostream>
using namespace std;

int main() {

	//变量的定义
	//语法:数据类型  变量名 = 初始值

	int a = 10;

	cout << "a = " << a << endl;
	

	return 0;
}

Operation result:

a = 10

Note: C++ When creating a variable, you must give the variable an initial value, otherwise an error will occur.

1.6.Constant

作用:用于记录程序中不可更改的数据

C++Two ways to define constants

  1. \#define Macro constant: #define 常量名 常量值

    • ==Usually defined at the top of the file==, representing a constant
  2. const-modified variable const 数据类型 常量名 = 常量值

    • ==Usually, the keyword const is added before the variable definition== to modify the variable as a constant that cannot be changed

Example:

//1、宏常量
#define day 7

int main() {

	cout << "一周里总共有 " << day << " 天" << endl;
	//day = 8;  //报错,宏常量不可以修改

	//2、const修饰变量
	const int month = 12;
	cout << "一年里总共有 " << month << " 个月份" << endl;
	//month = 24; //报错,常量是不可以修改的
	
	

	return 0;
}

Operation result:

一周里总共有 7 天
一年里总共有 12 个月份

1.7.Keyword

**Function:** Keywords are words (identifiers) reserved in advance in C++

  • When defining variables or constants, do not use keywords.

C++The keywords are as follows:

asm do if return typedef
auto double inline short typeid
bool dynamic_cast int signed typename
break else long sizeof union
case enum mutable static unsigned
catch explicit namespace static_cast using
char export new struct virtual
class extern operator switch void
const false private template volatile
const_cast float protected this wchar_t
continue for public throw while
default friend register true
delete goto reinterpret_cast try

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

1.8.Identifier naming rules

Function:C++When naming identifiers (variables, constants), there is a set of rules of its own.

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

Recommendation: When naming identifiers, strive to achieve the effect of knowing the meaning from the name, making it easier for yourself and others to read.

2.The Relationship Between C and C++ and the Learning Path

2.1.What are C and C++?

C and C++ are both general-purpose compiled programming languages. In addition, common programming languages include Python, Rust, Go, C# (pronounced C Sharp), Java, and JavaScript, among others; Shell, on the other hand, is mainly used for writing command-line and system administration scripts.

C++ It was originally developed from the C language, so the two share many similarities in basic syntax, operators, flow control, functions, and pointers. In some technical materials, toolchains, and job descriptions that involve both, people often use "C/C++" as a combined term.

However, C and C++ are now two languages with separately formulated standards and separate development, and cannot be simply understood as two versions of the same language:

  1. C++ is not "fully compatible with C". Most simple C code can be migrated to C++ relatively easily, but there is still some valid C code that cannot be compiled directly as C++.
  2. C++ is not just "C with classes". Modern C++ also includes templates, RAII, exceptions, lambdas, smart pointers, concurrency support, and a rich standard library.
  3. C is also not an outdated language that has been replaced by C++. C is still heavily used in operating systems, embedded development, drivers, low-level libraries, and cross-language interfaces.

Therefore, C and C++ share a common foundation, but each also has its own suitable programming style. Learning one can indeed help in understanding the other, but when writing C++, one should not merely copy C-style code.

Feature C language C++ language
Language positioning Small and streamlined, emphasizing direct expression of low-level operations Richer in features, supporting abstraction from low-level to high-level
Programming paradigm Mainly procedural programming Multi-paradigm: procedural, object-oriented, generic, functional, etc.
Resource management Usually manual allocation and release of resources Supports manual management, with RAII and smart pointers recommended
Abstraction and reuse Functions, structs, macros, and modular files Functions, classes, templates, generic algorithms, and the standard library
Standard library C standard library C++ standard library, which also provides support for most C standard library functionality
Type system Relatively simple, with some implicit conversions being more permissive Richer type system, usually providing stricter checks
Runtime efficiency Suitable for high-performance and low-level development Also suitable for high-performance development; reasonable abstraction usually introduces no additional overhead
Common scenarios Embedded systems, operating systems, drivers, low-level libraries Games, graphics, robotics, desktop software, infrastructure, and high-performance computing

The application scenarios in the table are not rigid boundaries. For example, embedded systems can also use C++, and large applications may also include C modules. The final choice of which language to use depends on project requirements, runtime environment, existing ecosystem, and team experience.

2.2.Should I learn C first, or directly learn C++?

Learning C++ does not require completing the study of C first. For readers of this tutorial, it is recommended to directly follow the C++ learning path:

  1. 先掌握变量、分支、循环、函数、数组和基本输入输出。
  2. 再学习引用、指针、结构体、类和对象。
  3. 接着学习 std::string、std::vector、迭代器和常用算法。
  4. 然后理解 RAII、智能指针、模板、Lambda 和异常处理。
  5. 最后结合 CMake、调试器、单元测试和第三方库完成真实工程。

If there is a need in the future to carry out embedded, operating system, driver, or pure C project development, then systematically supplementing the C language's arrays and pointers, memory layout, structures, preprocessor, and manual resource management will be more targeted.

This tutorial focuses on C++. When encountering syntax shared with the C language, it will be explained along the way, but examples will > as much as possible adopt a style suitable for modern C++, rather than treating C++ as a simple extension of the C language.

2.3.Supplementary Learning Materials

This tutorial mainly focuses on organizing knowledge points, engineering environments, and problems easily encountered in practice. Beginners can also learn by combining the following videos or documents:

  1. C++ video tutorial
  2. Peng Ge C language video
  3. Runoob: C language tutorial
  4. Runoob: C++ tutorial

Different materials may adopt different C++ standards and code styles. When learning the syntax, you may refer to multiple sources, but in the project of this tutorial, the C++ notation and CMake configuration given in the current chapter shall prevail.