Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference-related issue in C++

Tags:

c++

reference

In the "C++ programming language", there is an example

void g()
{  
   int ii = 0;
   int& rr = ii;
   rr++;
   int* pp = &rr;
}

The author states:

This is legal, but rr++ does not increment the reference rr, rather, ++ is applied to an int that happens to be ii.

I am quite confusing about this statement, why "rr++ does not increment the reference rr"? So rr is just used as "bridge" to increment ii?

like image 215
user785099 Avatar asked Jun 08 '26 16:06

user785099


2 Answers

Yes, in C++ a reference is nothing more than an alias, or a "bridge" as you say. Any time you say rr, it is as if you'd said ii, the "original" name of the variable that rr references.

That is different from references in many other languages (which behave more like C++'s pointers). In C++, references are not objects, they have no separate identity. You can't tell the reference to "please increment", or "please point to null" or anything else. It just becomes another name for the variable that the reference points to.

like image 84
jalf Avatar answered Jun 11 '26 13:06

jalf


A reference is similar to a dereferenced pointer to a variable. For example:

int v = 3;
int* pv = &v;
int& rv = v;

// Access v through a pointer:
*pv = 4;

// Access v through a reference:
rv = 4;

In this example, both statements will set v to 4.

like image 42
npclaudiu Avatar answered Jun 11 '26 12:06

npclaudiu