0

Maybe there is an answer to this, but I haven't found it, probably because I do not know what the correct title of my question is.

I'm starting to learn C++, and noticed that when initializing, modifying, and accessing, the behavior is the same in both of these lines.

int *p = &a;

and

int &p = a;

The only difference I see is that later when I use p in the first case, I have to write *p everytime, otherwise I get the address of (probably a since its value equals &a), whereas in the second case I can just write p without the asterisk.

Are those just different syntax for the same thing, or are they different but just happen to give me the same results (in my very basic tests)? Is the compiler doing the same thing in both cases?

Nick Bailuc
  • 101
  • 7
  • `int *p` means p is a pointer to an int. a pointer is like the street-address where the int lives. if you were to add 1 to the pointer, you go to the next house on the block. to look inside the house at the int inside you "dereference the pointer" by prepending an `*`. `int &p` means p is a reference to an int, which means it's a pointer that's always dereferenced for you. So if you add 1 to the reference, you actually increment the integer. – orion elenzil Nov 10 '21 at 23:28
  • 1
    Interpreting C++ is depends a LOT on context. In `int *p = &a;` the `&` means take the address of `a`, but in `int &p = a;` the `&` means `p` is a reference. The best way to get a good handle on all of the variations is to get a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and learn the language carefully. – user4581301 Nov 10 '21 at 23:29
  • It is highly unlikely that both things would appear, side by side, in your C++ textbook. So, can you provide further details about what in your C++ textbook is unclear? Picking random C++ code, and then asking what it does, is not a very good way to learn C++. C++ is the most complicated general purpose programming language in use today, and for these kinds of questions about C++ fundamentals we normally direct people to their textbook for a complete explanation. It wouldn't make a lot of sense to cut/paste entire textbook chapters for answers, here. – Sam Varshavchik Nov 10 '21 at 23:31
  • 1
    A pointer will be a pointer. A reference is an alias, and if the compiler can optimize it away to be nothing more than just a synonym, it may very well do so; or a compiler may implement a reference as a pointer (under the covers) in some circumstances. (Such an implementation detail is not exposed, and cannot be acted upon programmatically... well, or at least not reliably & portably.) – Eljay Nov 10 '21 at 23:34
  • 1
    The behaviour is NOT the same. In the first case, `p` is a pointer - a variable whos value is the address of an `int` (like `&a`). In the second, `p` is a reference to (alternative name for) `a`. While both can be used to access or (e.g. since not qualified `const`) modify the value of `a`, they have different meaning, and the circumstances in which one is preferred over the other differ. A pointer can be reassigned (e.g. to contain the address of a different `int`) and can be null (point at nothing). A reference cannot be reassigned (always refers to the same `int`) and cannot be null. – Peter Nov 10 '21 at 23:37
  • @SamVarshavchik im not picking random code, this is from a list of extra questions my prof posted. Idk why you ask what in my textbook is unclear, i didnt mention anything about a textbook I asked because I was unsure if they were different or just different syntax (C++ is very liberal with its syntax) – Nick Bailuc Nov 10 '21 at 23:42
  • Where Sam is headed is trying to learn C++ without using a decent text book is a very difficult task. If you don't have one you'll need a professor that's in the top percentile of C++ educators and has a LOT of free time to lavish on you. Get a good book if you don't have one already, work your way through it slowly and carefully, and learning C++ will take far less time than asking questions about every bit of odd syntax you stumble across. There is a lot of odd syntax in C++. – user4581301 Nov 11 '21 at 00:01
  • @user4581301 "There is a lot of odd syntax in C++". Yeah! It's become progressively more odd as the language and standards have evolved too, and I expect that to continue. I suspect language lawyers and folks involved directly in evolving the standard have a *hankering* for odd syntax, so the rest of us are doomed. – Peter Nov 11 '21 at 00:22
  • There was [a wonderful joke](https://www-users.cs.york.ac.uk/susan/joke/cpp.htm) a few decades ago about how the "insane" syntax of C++ was there to keep programmers earning good wages. – user4581301 Nov 11 '21 at 00:31
  • If this is from "a list of extra questions" posted by your professor, then this must mean that the questions are rooted in the material that the professor has presented in class, on the topic of pointers and references in C++, and you are expected to come up with the answer based on that information. It's very unlikely that your professor gave you this "list of extra questions" out of thin air. It must be based on previously taught class material. So, what specifically in your professor's class notes, or other learning material, that was unclear? – Sam Varshavchik Nov 11 '21 at 00:36

2 Answers2

1

Actually, that depends on your program!

For example:

a = 123;
b = 456;
int *p = &a;

// bunch of statements here

if (condition) { p = &b; }
do_stuff(*p);

You can't do this with a reference: Once it's set, it's set.

Another difference of pointers and references in C++ is that (const) references can extend the lifetime of temporary objects:

foo f() { 
  foo inner_foo;
  return inner_foo;
}

const foo_ref& = f();

if the function were to return a pointer to inner_foo:

foo* f() { 
  foo inner_foo;
  return &inner_foo;
}

const foo* p = f();

you would have a pointer to a destructed foo, in a place on the stack that may get used by other variables.

And there are other differences between pointers and references.

You may also want to read the following items in the C++ Super-FAQ:

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • "*You can't do this with a reference*" - actually, in a way, you can, if you use the `condition` in the initialization of the reference, eg: `a = 123; b = 456; int &r = (condition) ? b : a; do_stuff(r);` – Remy Lebeau Nov 10 '21 at 23:41
  • @RemyLebeau: That's not exactly the same, and it depends on having the two values available in the same statement. – einpoklum Nov 10 '21 at 23:42
0

The first is a pointer to an object, in your example to an int named a. A pointer holds the memory address of an object in memory. You would have to dereference the pointer in order to access the object it is pointing at.

The second is a reference to an object, in your example to a. A reference is an alias 1, ie another name, for an object. So the two names are effectively referring to, and thus are treated as, the same object, which is why you can use p to access a without dereferencing p.

1: though, most compilers will implement a reference using a pointer, but this is an implementation detail and should not be relied on in code logic.

Another difference is that a pointer can be set to nullptr, and can also be re-assigned to point at a different memory address, eg:

int a, b;
int *p = nullptr;
...
p = &a;
...
p = &b;

Whereas a reference cannot do either of those things. Once initialized, a reference cannot be changed to refer to another object.

As such, taking the address of a reference with operator& will return the address of the object it refers to, whereas taking the address of a pointer will return the address of the pointer itself, not the object it points at.

Likewise, assigning a value to a reference will assign to the object it refers to, whereas assigning a value to a pointer will assign to the pointer itself, not the object it points at.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770