l-values and r-values and r-value references

I am slowly trying tolearn c++ sand have moved onto the above topic. Please see below. Can someone explain ot to me please...

Thanks in advance


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
 
//return l-value
int &Transform(int &x){
    x *= x;
    return x;
}

int main(int argc, const char * argv[]) {
   
    
    //in the eaxmple below x is l-value; 5  r-value
    int x {5};


    Transform(x) = 50;

    return 0;
}



Last edited on
Hello jamesfarrow,

Try this and see what you get:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

//return l-value
int &Transform(int &x)
{
	x *= x;
	return x;
}

int main(int argc, const char * argv[])
{

	//in the eaxmppe below x is l-values; 5  r-values
	int x{ 5 };

	std::cout << x << '\n';

	Transform(x) = 50;

	std::cout << x << '\n';

        std::cin.get();

	return 0;
}


Adding these two lines will give you an idea of hat is happening.

In line 14 x is set to 5.

Line 18 calls the function with "x equal to 5".

If you put a break point on line 7, when run in debug mode, you would find that "x is equal to 25". Since the function returns a reference that makes line 18 lhs of = a function call and a variable that is set equal to 50.

The two cout statements will show the value of "x" before and after the function call.

If I have something wrong someone will let us know.

Hope that helps,

Andy
Hi Andy

Thanks for your answer, I have ran through it like you said. I can see what is happening, what I dont understand is - it doesnt make any sense to me? Where would anything similar to above be useful? Bearing in mind I am a novice at all this.

Hello jamesfarrow,

I can not say that I have come across this before and other than a learning tool I can not think of any real use for something like this.

That said maybe someone with more experience may have used something like this or know of a use.

Andy
Thnaks Andy - I couldnt see it being of any use either but...
At least I have learned something 👍🏻
Topic archived. No new replies allowed.