C/C++ Call By Reference

Asked 2 years ago, Updated 2 years ago, 25 views

#include <iostream>
using namespace std;

int getInput(int *a, int *b, int *c){
    cin >> *a;
    cin>> *b;
    cin>> *c;
    return 0;
}

int maxmin(int n1, int n2, int n3,int *max2, int *min2){
    *max2 = (n1 > n2) ? (n1 > n3 ? n1 : n3) : (n2 > n3 ? n2 : n3);
    *min2 = (n1 < n2) ? (n1 < n3 ? n1 : n3) : (n2 < n3 ? n2 : n3);
    return 0;
}

int main() {
    int num1, num2, num3;
    int max, min;
        getInput(&num1, &num2, &num3);
        maxmin(num1, num2, num3, &max, &min);
        cout<<"The gap between "<<max<<" and "<<min<<" : "<<max-min<<endl;
        return 0;
}

Can I change the source code in the maxmin function to the if format? Also, in this code, &. * I don't know what is. Are the max(num1,num2,num3) values the numbers entered in the getInput function?

c c++

2022-09-20 19:48

2 Answers

1) Can I change the source code in the maxmin function to the if format if?

*max2 = (n1 > n2) ? (n1 > n3 ? n1 : n3) : (n2 > n3 ? n2 : n3);
if(n1>n2){
    if(n1>n3){
     *max2 = n1;
    }
    else {
    *max2 = n3;
}

}
else{
    Similar to the above
}

2) Also, I don't know what &.* is in this code. Are the max(num1,num2,num3) values the numbers entered in the getInput function?

If you study C++ pointers and references a little more, you'll understand easily ^ If you search on Google, you can see everything.

^

And in short, it's not just copying the num1 value, it's passing the address itself *(pointer) goes to that address and looks at the value inside


2022-09-20 19:48

In systems such as C, C++, variables typically have life times, such as the generation and destruction of functions to which they belong.

Variables are created and managed in the stack. When the function ends, all the variables in that stack disappear.

However, you may want to preserve the variable even if the function terminates. In that case, a variable is created in heap memory, not stack. That's what the new operator does.

So the program doesn't know where the value of this variable is because it's not managed by stack.

So you have to tell us where this variable is, and that's the pointer.

At this point, * and & are highly associated with pointers.

I don't think you'll understand even if I say this, and I think you'll find out naturally if you think more about it and program it.

There are no other parameters. If there's anything else, it's just that I get it with a pointer.


2022-09-20 19:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.