I'd like to talk about pointers.

Asked 2 years ago, Updated 2 years ago, 50 views

Regarding the pointer, I have a question due to lack of study

I don't know if it's the correct syntax because I don't have an environment where I can use my smartphone right now.

 void f(int*a) {*a=5;}

int main() {
 intx = 1;
  f(&x);
  printf("%d", x);
  return 0;
}

I think the result at this time will be 5.

 void f(int&a) {a=5;}

int main() {
 intx = 1;
  f(x);
  printf("%d", x);
  return 0;
}

I'm sorry I didn't try it properly...

I think both will be 5
I don't understand the difference between the above writing method and the below writing method
Are there any differences between the generated object files?

Also, where is the better?

c++ pointer

2022-09-29 22:22

2 Answers

The former is a pointer, and the latter is referred to as reference.
For pointers, NULL or nullptr can be passed, which can be a hotbed of bugs, but for references, it is syntactically harder to pass NULL, making it safer than pointers.

In the case of pointers, it is unclear whether they point to a single value or the beginning of an array, but in the case of references, it is also a safe statement to distinguish clearly.

voidf(int*a);// Pointer pointing to a single or array head
void f(int&a);// single reference
voidf(int(&a)[10]);// Browse Array

The pointer exists in both C and C++ languages, but references are only in C++ languages and not in C languages.You can also omit the return value in C language or define the function later, but you cannot omit the return value in C++ language and must declare it first.


2022-09-29 22:22

The final generated machine language is optimized for high intensity and
when in non-debug mode. Most of the processing systems are the same for reference and pointer.
(I can't think of a situation where a different machine language is inevitable.)
"Therefore, I am sure that there is no ""operating speed superiority"" at all."

"Is ""source code description superiority and inferiority"" depending on the situation?"
It is often safer to refer to only the new ones.
Pointers have always been more familiar ( language users).
A pointer can pass nullptr, which is both a drawback and an advantage.
The pointer can handle the whole array by passing the "head of the array", but it is also a drawback and an advantage.

has no reference, so you must use a pointer.
to eliminate pointer usage and write source for reference only.
(Maybe it's a bit misleading...)
But if you don't use any pointers in the first place, you'll see


© 2024 OneMinuteCode. All rights reserved.