搜尋此網誌

2025年8月21日星期四

Passing values to a function

It’s not that one is universally better --- pointers and references are different tools, each with its own strengths and trade‑offs. The “better” choice depends on your intent and the constraints of your code.

trade-off: the act of balancing two things that are opposed to each other

In C++, “taking an argument” usually means receiving input values into a function so it can work with them.

In C++, the return statement is how a function hands control (and optionally a value) back to its caller. Think of it as the function’s “exit door” — once return runs, the function stops executing immediately.

For void functions, you can:
- Omit return entirely, or
- Use return; to exit early without a value:

In main
- return 0; → program ended successfully
- Non‑zero values (e.g., return 1;) → indicate an error or abnormal termination to the operating system

In C++, the difference between taking arguments by address (pointers) and by reference is as follows:

By Address (Pointers):

You pass the memory address of the variable.
Syntax: Use an asterisk * in the function parameter and an ampersand & when calling the function.
Example: void swap(int *x, int *y) and called with swap(&a, &b).
Requires dereferencing inside the function using the * operator.

By Reference:

You pass the variable itself, but it acts as an alias to the original variable.
Syntax: Use an ampersand & in the function parameter.
Example: void swap(int &x, int &y) and called with swap(a, b).
No need for dereferencing inside the function.

Using references is generally safer and simpler because it avoids the need for explicit pointer manipulation.

Mainly by Microsoft Copilot

沒有留言:

發佈留言