1

I am currently going through the Getting started with C++ learning path on LinkedIn. I had some confusions regarding pointers and references so I visited this link on SO.

This link further confuses me, because based on the course the syntax for references is type followed by ampersand. ie int& my_reference = my_int; However, i see posters using int& or float &sum = total; on that link. This confuses me as I cant tell if it is reference or address of operator for pointers.

and if float &sum = total; is valid declaration of a reference, is it that address of operator for pointers is only valid on the RHS of the expression? Meaning I cannot manually allocate the address of a variable to some other address as follows int &my_int = [new address here], but a pointer that points to memory address is allowed ptr = &my_int;?

Tan Yu Hau Sean
  • 585
  • 6
  • 16
  • 1
    Think of a reference as an *alias* for some**thing** else. And as a pointer as (like the name implies) like something that points some**where** else. When you use a reference, it's like using the actual thing it references. When you use a pointer you must dereference it to get to the thing it points to. – Some programmer dude Jan 15 '23 at 07:49
  • 4
    Or is the problem the difference between e.g. `int& ref` versus `int &ref` (and even `int & ref` and `int&ref`)? Then there is ***no*** difference. They are all exactly the same. – Some programmer dude Jan 15 '23 at 07:51
  • 1
    does this mean that the & operator only behaves as address-of when on the RHS? – Tan Yu Hau Sean Jan 15 '23 at 07:52
  • 4
    Yes, you can have `int& ref = something;` and you can have `int* pointer = &something;`. They meaning of `&` depends on the context (and we should not forget the bitwise AND operator which is *also* `&`). – Some programmer dude Jan 15 '23 at 07:53
  • This may be a bit of an advanced topic, but you can actually check, if the type of a variable is as expected by using `decltype` + `std::is_same_v` (from the `type_traits` standard library header) in combination with `static_assert`. Demo: https://godbolt.org/z/adch3nqo1 – fabian Jan 15 '23 at 09:12

1 Answers1

2

Some people prefer their reference/pointer symbols aligned to to left, some to the right.

int my_int = 5;
// references
int& my_reference = my_int;
int &my_reference = my_int;

// pointers
int* my_ptr = &myptr;
int *my_ptr = &myptr;

It still means the same.

rgnt
  • 551
  • 2
  • 7