Home  >  Article  >  Backend Development  >  Analysis of confusing concepts in C++ syntax

Analysis of confusing concepts in C++ syntax

WBOY
WBOYOriginal
2024-06-01 21:13:00631browse

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

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

  • A pointer is a variable that stores the address of another variable.
  • A reference is an alias that points directly to another variable.

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

  • Passing by value transfers the function A copy of the parameters is passed to the function.
  • Pass by reference passes the reference of the function parameter to the function.

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

  • const declares a constant variable ( Unchangeable).
  • constexpr declares a compile-time constant whose value is known at compile time.

Example:

const int x = 5; // x 是运行时常量
constexpr int y = 5 + 1; // y 在编译时已知,值为 6

int main() {
  // x 是常量,不可修改
  // x = 10; // 错误:无法修改常量

  // y 是编译时常量,无法修改
  // y = 10; // 错误:无法修改编译时常量
}

4. && and &

  • && are logical AND operators (returns a boolean value).
  • & is the reference operator.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn