#include <iostream>
using namespace std;
void Plus(int * num)
{
++*num;
}
void reverse(int * num)
{
*num *= -1;
}
int main()
{
int num = 10;
int num1 = -9;
Plus(&num);
Plus(&num);
Plus(&num);
Plus(&num);
reverse(&num1);
cout << num << endl;
cout << num1 << endl;
return 0;
}
Here, the num value should be output as 14 Plus function content If *num++; is used, the value of num is still 10 output Use the Plus function as a reference void Plus(int &num) { num++; } If you do this, you get 14. If you use a reference to num++, it becomes 14 I wonder why it becomes 10 if you use a pointer to *num++.
c++
It is necessary to compare the priorities of rear ++
and *
.
http://en.cppreference.com/w/cpp/language/operator_precedence
If you look here, you can see that post ++
has a higher priority.
void Plus(int* num) {
*num++;
}
If you solve the above function to make it easier to understand, it becomes a function below.
void Plus(int* num) {
int* temp = num;
*temp
num = num + 1;
}
This means that no increment applies to the integer of the address you enter.
Therefore, the value of num
is not modified.
void Plus(int& num) {
num++;
}
In this case, since it is a reference type, the increment operation is applied to the variable you entered to make 14.
© 2024 OneMinuteCode. All rights reserved.