第 1 節

C++ Basics

0瀏覽次數0訪問次數--跳出率--平均停留

Introduction to C++

First C++ Program

Writing a C++ program under Linux can be divided into 4 steps

  • Create Directory
  • Create file
  • write code
  • Compile and run the program.

Create Directory

First, create a separate directory to store the current example:

mkdir hello_cpp
cd hello_cpp

Create file

Create a main.cpp file:

touch main.cpp

write code

#include<iostream>
using namespace std;

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

    cout << "Hello world" << endl;


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

Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.

Compile and run the program.

Compile using g++, then run the generated executable file:

g++ main.cpp -std=c++17 -Wall -Wextra -o main
./main

Terminal output

Hello world

The parameters of the main function

main functions do not necessarily have to take parameters. The two most common ways to write them are:

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

Run/Observations: This is the most concise program entry point, suitable for programs that don't need to read command-line arguments.

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

Running/Observing Results: This is also the standard way to write a program entry point, suitable for programs that need to read command-line arguments.

Among them:

  • argc represents the number of command-line arguments, usually at least 1, because the program's own path is also counted as an argument.
  • argv represents the command-line argument array, where argv[0] is typically the program's own path or name, and user-provided arguments start from argv[1].
  • char* argv[] can also be written as char** argv—both express the same meaning here.

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;
}

运行结果:见下方“运行结果”;argv[0] 会随启动方式不同而变化,重点观察 argc 和各个 argv 的对应关系。

Compile and run:

g++ main.cpp -std=c++17 -Wall -Wextra -o args_demo
./args_demo hello 123

Results

argc = 3
argv[0] = ./args_demo
argv[1] = hello
argv[2] = 123

Note: argv[0] depends on the startup method—it could be ./args_demo or a full path. Typically, when processing parameters, user input is read starting from argv[1].

Annotation

Purpose: Add explanations and annotations in the code to facilitate readability for yourself or other programmers.

Two Formats

  1. Single-line comment: // 描述信息
    • Typically placed above a line of code or at the end of a statement, ==as a comment describing the code==.
  2. Multi-line comments: /* 描述信息 */
    • Usually placed above a block of code, ==as a general description of that code==.

Note: The compiler ignores the contents of comments while compiling code.

variables

Function: Names a specific memory space to facilitate easier manipulation of that memory segment.

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

Example:

#include<iostream>
using namespace std;

int main() {

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

    int a = 10;

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

    return 0;
}

Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.

Note: When creating variables in C++, you must assign them an initial value; otherwise, an error will be thrown.

constant

Function: Used to record unchangeable data in a program.

There are two primary ways to define constants in C++. The first is using the const keyword, which is type-safe and commonly preferred:

const double PI = 3.14159;

The second method uses the preprocessor directive #define, inherited from C, which does not respect scope or type:

#define PI 3.14159

In modern C++, a third option, constexpr, is also available for compile-time constants:

constexpr double PI = 3.14159;

The const and constexpr methods are generally recommended for better type safety and debugging.

  1. #define macro constant: #define 常量名 常量值
    • ==Typically defined at the top of the file==, represents a constant
  2. const modified variable const 数据类型 常量名 = 常量值
    • ==Typically add the const keyword before the variable definition==, to modify the variable as a constant, unmodifiable

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;
}

Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.

Keywords

Purpose: Keywords are predefined reserved words (identifiers) in C++

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

The C++ keywords are as follows:

asmdoifreturntypedef
autodoubleinlineshorttypeid
booldynamic_castintsignedtypename
breakelselongsizeofunion
caseenummutablestaticunsigned
catchexplicitnamespacestatic_castusing
charexportnewstructvirtual
classexternoperatorswitchvoid
constfalseprivatetemplatevolatile
const_castfloatprotectedthiswchar_t
continueforpublicthrowwhile
defaultfriendregistertrue
deletegotoreinterpret_casttry

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

Identifier Naming Rules

Purpose: C++ has its own set of rules for naming identifiers (variables and constants).

  • An identifier cannot be a keyword.
  • Identifiers can only consist of letters, numbers, and underscores.
  • The first character must be a letter or underscore
  • Identifiers are case-sensitive.

Suggestion: When naming identifiers, aim for intuitively clear names to facilitate reading for yourself and others.

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

C++ evolved from C, retaining much of C's syntax and low-level memory manipulation capabilities. C++ extends C with object-oriented programming (OOP), templates, the Standard Template Library (STL), and numerous other features, making it suitable for more complex and large-scale software development.

Suggested Learning Path:

  1. Start with C Fundamentals: Master core concepts like variables, data types, control flow (loops, conditionals), functions, arrays, pointers, and dynamic memory management.
  2. Transition to C++: Learn C++ by building on your C knowledge. Focus on key differentiators:
    • OOP Principles: Classes, objects, inheritance, polymorphism, and encapsulation.
    • Modern C++ Features: Start with auto, range-based for loops, and smart pointers, then progress to move semantics and lambda expressions.
    • STL: Become proficient with containers (vector, map, list), algorithms, and iterators.
  3. Advanced Topics & Practice: Deepen your understanding of templates, exception handling, multi-threading, and best practices. Apply your knowledge by working on projects that solve real problems.

Key Takeaway: While you can learn C++ directly, having a solid foundation in C provides a deeper understanding of how computers work at a lower level, which is invaluable for systems programming, performance-critical applications, and embedded development.

C/C++ Introduction:

C and C++ are two high-level computer languages. Other common high-level languages include Python, Rust, Go, C# (C Sharp, C++++), Java, JavaScript, Linux Shell, and more.

C++ is built upon the C language by adding features of modern programming languages such as object-oriented programming and templates. The two languages are very similar in terms of syntax rules, as well as the number and usage of operators, which is why they are often collectively referred to as "C/C++".

C and C++ are not opposing competitors:

  1. C++ is an enhancement of C, a better version of C. In fact, C++ and C are different versions of the same language.
  2. C++ is built on C and is fully compatible with C's features.

Learning C and C++ can reinforce each other. Mastering C lays a solid foundation for further learning of C++, while studying C++ deepens our understanding of C, enabling us to use it more effectively.

FeaturesC languageC++ language
Programming paradigmProcess-orientedMulti-paradigm, supports object-oriented programming.
Memory managementManual managementManual management, providing RAII (Resource Acquisition Is Initialization)
Code reusabilitylowerHigh, implemented through classes, inheritance, templates, etc.
Standard libraryStandard C libraryStandard Template Library (STL) and C Standard Library
Operational efficiencyHighSlightly lower than C, but the gap is not significant.
Application scenariosOperating systems, embedded systemsGame development, graphics processing, large-scale applications
Type checkingrelatively looseStricter, providing more type checking.

This post only provides guidance on certain issues. For learning C/C++, please primarily refer to the following videos:

C/C++ Environment Configuration: Complete Electrical Control Group Environment Setup Guide

  1. C++ video tutorial:

https://www.bilibili.com/video/BV1et411b73Z

  1. Brother Peng's C Language Video:

https://www.bilibili.com/video/BV1cq4y1U7sg

  1. Beginner's Tutorial:

https://www.runoob.com/cprogramming/c-tutorial.html

https://www.runoob.com/cplusplus/cpp-tutorial.html

音乐页