Confusion concept analysis: pointers and references: Pointers store variable addresses, and references point directly to variables. Pass-by-value and pass-by-reference: Pass-by-value copy, pass-by-reference reference. const and constexpr: const is a run-time constant, and constexpr is a compile-time constant. && and &: && and &&& are logical AND operators, and & is a reference operator.
Analysis of confusing concepts in C++ syntax
Introduction
C++ is A powerful programming language, but its syntax can be confusing at times. This article will explore several commonly confused concepts and provide examples of how to use them correctly.
1. Pointers and references
Example:
int x = 5; int* ptr = &x; // ptr 指向 x int& ref = x; // ref 是 x 的引用 cout << *ptr << endl; // 输出 5 cout << ref << endl; // 输出 5
2. Passing by value and passing by reference
Example:
void swap(int x, int y) { int temp = x; x = y; y = temp; } void swap_ref(int& x, int& y) { int temp = x; x = y; y = temp; } int main() { int a = 5, b = 10; cout << "Before swap:" << endl; cout << "a: " << a << ", b: " << b << endl; swap(a, b); cout << "After swap:" << endl; cout << "a: " << a << ", b: " << b << endl; // a 和 b 仍然为 5 和 10 swap_ref(a, b); cout << "After swap_ref:" << endl; cout << "a: " << a << ", b: " << b << endl; // a 和 b 已交换为 10 和 5 }
3. const and constexpr
Example:
const int x = 5; // x 是运行时常量 constexpr int y = 5 + 1; // y 在编译时已知,值为 6 int main() { // x 是常量,不可修改 // x = 10; // 错误:无法修改常量 // y 是编译时常量,无法修改 // y = 10; // 错误:无法修改编译时常量 }
4. && and &
Example:
bool flag = true; // 逻辑与运算 if (flag && (x > 0)) { // ... } // 引用运算符 int& ref = x; // ref 是 x 的引用
The above is the detailed content of Analysis of confusing concepts in C++ syntax. For more information, please follow other related articles on the PHP Chinese website!