Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Const reference to return value of a function | C++

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading