this post was submitted on 03 May 2024
245 points (94.2% liked)

Programmer Humor

32472 readers
467 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 

Alt text:

Image that says:

HOLY SHIT!! IS THAT A MOTHERF*CKING C++ REFERENCE???

int& a = b;

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 28 points 6 months ago* (last edited 6 months ago) (5 children)

I've used C but never C++. What does it mean for a variable's type to be int&? From when I've used it, & would be used to create a pointer to a variable, but the type of that pointer would be int*.

edit:

never mind, I looked it up. It's a "reference" instead of a pointer. Similar, but unlike a pointer it doesn't create a distinct variable in memory of its own.

[–] [email protected] 5 points 6 months ago (3 children)

never mind, I looked it up. It’s a “reference” instead of a pointer. Similar, but unlike a pointer it doesn’t create a distinct variable in memory of its own.

I'm almost sure it does create a distinct variable in memory. Internally it's still a pointer, specifically a const pointer (not to be confused with a pointer to a const value; it's the address that does not change). Think about it as a pointer that is only ever dereferenced and never used as a pointer. So yes, like the other commenter said, like an alias.

[–] [email protected] 3 points 6 months ago (2 children)

I don't think references are variables: you can't modify them, and AFAIR you can't have pointers to them, with the possible but unlikely exception of non-static member references.

[–] [email protected] 6 points 6 months ago

An int& reference is just as much of a variable as int* const would be (a const pointer to a non-const int). "Variable" might be a misnomer here, but it takes just as much memory as any other pointer.

load more comments (1 replies)
load more comments (1 replies)
load more comments (2 replies)