confused on refs and pointers

I must be confused because references cant be bound to literals but I ran code from C++ primer 5th edition and it seems to me last line is assigning R2 reference to *p which I *think is a literal.The last line is mine, just trying to figure this crap out.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <iostream>

int main()
{
	int i = 42;
	int &r = i;
	int *p;
	p = &i;
	*p = i;
	int &r2 = *p;
std::cout << "r2=" << r2 <<" deref p="<<*p<< std::endl;
}

Last edited on
The p has address of i. Therefore, the *p is i and int &r2 = *p; is same as int &r2 = i;


PS. The *p = i; is effectively i = i;.
Last edited on
The real behavior of references is substantially more complicated and subtle, but I am told that C++ Primer tries not to discuss it until later when enough prerequisite knowledge is available to understand it.

For now, know that any discussion of references involves some approximation.

This facet of the behavior actually depends on a property of expressions called value category. Plain-old references to non-const (also known as lvalue references to non-const like r) can only bind to expressions whose value category is lvalue.
I think I understand what both of you are saying but... I guess what I'm asking is,
is r2(a reference)=I=42?
> is r2(a reference)

Yes. The type of the variable r2 is 'lvalue reference to int'


> *p which I *think is a literal

*p is not a literal. It is a non-literal expression; it yields an lvalue of type int
Ok, thank you all, JLBorges showed me the light, for some reason I was thinking reference could only take an address and no values(literal or variable) :/.

I really really don't like this book, I've read the reference section 3 times and it's going in but man is it slow, making me feel like I need the cpp for dummy book
Last edited on
Topic archived. No new replies allowed.