I recently learnt about rvals, lvals, references, const references and am confused about what is happening in this piece of code. I am not even sure if its something to do with rval/lval or other paradigm.
Please explain the two outputs:
#include<bits/stdc++.h>
using namespace std;
int main(){
int x=6;
int y=5;
const int &mx = max(x, y);
const int &mn = min(x, y);
// x = 0;
// y = 1;
// cout << mx << mn; // outputs: 01
x = 0;
cout << mx << mn; // outputs: 05
}
Thanks!
>Solution :
std::max and std::min returning references to the min/max values as documented here: std::max
If you keep the references instead of the values, any modification of the input variables after the call of the both functions will still modify the value of the kept references.
If you use a debugger, you can see the address which the reference variable points to. Maybe that makes it easier to understand.