1 Variables
In C++, a variable is the basic unit for storing data, having a specific type and name. Below is a detailed introduction to C++ variables:
Declaration and Definition of Variables
·Declaration: Informs the compiler of the variable’s type and name without allocating memory.
·Definition: Allocates memory for the variable, which can also be initialized at the same time.
Variable Types
·Basic types: Include integer types (such as int, short, long, etc.), floating-point types (such as float, double), character types (such as char), and boolean types (bool).
·Composite types: Such as arrays, structures, classes, etc.
·User-defined types: Custom types created using class or struct.
Variable Naming Rules
·Variable names must be unique.
·Can only contain letters, numbers, and underscores, and cannot start with a number.
·Cannot use C++ keywords.
Variable Scope and Lifetime
·Scope: Determines the visibility range of the variable in the program, such as local scope, global scope, etc.
·Lifetime: The duration of the variable’s existence, from definition until it goes out of scope or is destroyed.
Variable Initialization
·Variables can be initialized at the time of definition, assigning an initial value.
·Uninitialized variables may contain indeterminate values and should be avoided.
Variable Usage
·Variables can be used to store and manipulate data, supporting various arithmetic and logical operations.
·The value of a variable can be modified during program execution.
Qualifiers
·const: Declares a constant whose value cannot be changed during program execution.
·volatile: Indicates that the value of the variable may be changed externally, preventing compiler optimization.
Example
cpp
#include<iostream>
int globalVar = 10; // Global variable
intmain() {
int localVar = 5; // Local variable
std::cout<< “Global variable: “ << globalVar << std::endl;// Output
std::cout << “Local variable: “ << localVar << std::endl; // Output
return0;
}}
1.1Unsigned Types
In C++, an unsigned type variable is one that can only store non-negative integers. Below is a detailed introduction to unsigned type variables in C++:
Declaration of Unsigned Type Variables
·Declare an unsigned type variable by adding the unsigned keyword before the type.
·For example, unsigned int a; declares an unsigned integer variable a.
Range of Unsigned Type Variables
·The range of unsigned type variables is double that of the corresponding signed type variables, as they do not use the highest bit to represent the sign.
·For example, the range of unsigned short is from 0 to 65535, while short ranges from -32768 to 32767.
Usage Scenarios for Unsigned Type Variables
·Suitable for representing values that are never negative, such as array indices, counters, or memory addresses.
·In embedded systems, due to limited resources, unsigned type variables are often used for data processing.
·On certain hardware platforms, unsigned operations may be more efficient than signed operations.
Operations on Unsigned Type Variables
·When performing operations between unsigned type variables and signed type variables, the signed type variable is automatically converted to an unsigned type.
·The result of subtraction with unsigned type variables is always non-negative, even if the result is mathematically negative.
Example
cpp
Dark Mode
Copy
#include<iostream>
intmain() {
unsignedshort us = 65535;
std::cout << “Unsigned short: “ << us << std::endl;
us++;
std::cout << “After increment: “ << us << std::endl; // Output 0, because 65535 is the maximum value of unsigned short
return0;
}
1.2Pointers
Pointers are a very important concept that allows programs to directly manipulate memory addresses. Below is a detailed introduction to pointers in C++ and their applications:
Basic Concept of Pointers
A pointer is a variable that stores the memory address of another variable. Through pointers, data in memory can be accessed and manipulated directly.
Definition and Initialization of Pointers
·Declaration format:Data type * Pointer variable name.
·Initialization: A pointer must point to a valid memory address, which can be the address of a variable or dynamically allocated memory. Uninitialized pointers are dangerous and may cause program crashes.
Pointer Operations
·Addition and subtraction: Pointers support addition and subtraction, but the unit is the size of the data type pointed to by the pointer. For example, int* p increments the actual address by 4 bytes (the size of the int type).
·Dereferencing operation: The * operator can be used to access the value at the memory location pointed to by the pointer.
Applications of Pointers
1.Dynamic memory management
·Use new and delete operators to dynamically allocate and free memory.
·Smart pointers (such as std::unique_ptr and std::shared_ptr) automatically manage memory, preventing memory leaks.
2.Function parameter passing
·Passing function parameters by pointer can avoid large data copies, improving efficiency.
·Enables reference passing, allowing functions to modify variables provided by the caller.
3.Implementing polymorphism and object-oriented programming
·A base class pointer can point to derived class objects, achieving runtime polymorphism.
4.Accessing array elements
·The array name is the address of the first element of the array, and pointers can be used to access elements within the array.
5.Implementing complex data structures
·Data structures like linked lists and trees require pointers to connect different nodes.
Special Types of Pointers
1.Null pointer
·A pointer that does not point to any valid memory address, usually initialized to nullptr (C++11 and later) or NULL (C++98 and earlier).
2.Constant pointer
·A pointer that points to a constant, cannot modify the value pointed to through the pointer, but the pointer itself can point to other addresses.
3.Pointer constant
·The pointer itself is constant, and once initialized, cannot change its pointing, but can modify the value pointed to through the pointer.
4.Function pointer
·A pointer that points to a function, can be used to call the function or passed as a parameter to other functions.
5.void pointer
·Can point to any type of pointer, but needs to be typecast before use.
Precautions
·Avoid using uninitialized pointers to prevent dangling pointer issues.
·Be aware of the pointer’s lifetime to avoid dangling pointers (pointers pointing to freed memory).
·Using smart pointers can effectively prevent memory leaks and pointer management errors.