This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 7 years ago.
I have a kinda deep C experience but I am a C++ beginner. References seem to be easier to use than pointers, but it drives me crazy. I think all references can be replaced with pointers. In my case, pointers are not that hard because I spent tons of times studying them. Is it common among C++ programmers to use references or is it just recommended??
One thing that references prevent is NULL pointers. If you want to ensure that a parameter passed to a function is not NULL, you can pass by reference.
void func(int& i); // i cannot be NULL
References cannot always be replaced by pointers:
C a, b, c;
a = b - c;
If there is an operator-() for C, it either needs to receive its arguments:
by copy:
C operator-(C left, C right);
by address:
C operator-(C* left, C* right);
in which case the call becomes:
a = &b - &c;
(which already has a meaning in C)
or by using a new construct that has no equivalent in C. This became references in C++.
There are a variety of questions you can refer to concerning the use of references versus pointers.
Related
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 4 years ago.
I understand the pointer concept (int*), but I cannot understand int& because they give the same result. What does int &data exactly mean?
void add1(int *data){
(*data)++;
}
void add2(int &data){
data++;
}
int main()
{
int i=0;
add1(&i);
printf ("value i = %d\n",i) // show 1
add2(i);
printf ("value i = %d\n",i); // show 2
return 0;
}
The function signature:
void add2(int &data)
is the pass-by-reference facility in C++. It's a way to allow the function to change the value passed in and have that change reflected back to the caller. In C, upon which C++ was originally based, all paramaters are pass-by-value, meaning the functions get a local copy which, if changed, does not affect the original value passed in.
As an aside, pass by reference is probably the one facility I'd most like to see added to C (not full-blown C++ references, just in the function calls) since I'm pretty certain 42% of all C questions here on SO have to do with pointers :-)
The way to do pass-by-reference in C and C++ can be seen in the lines below. The first is the right way to do it in C++, and the second is the "pointer gymnastics" poor C developers have to go through to get the same effect:
void FortyTwo(int &x) { x = 42; } // Call with FortyTwo(variable);
void FortyTwo(int *pX) { *pX = 42; } // Call with FortyTwo(&variable);
In the latter, the pointer is passed by value but you can use that pointer to get at (and change) the data it points to. In C++, you should, as much as possible, avoid passing the pointers to values you want to change since that's one of the reasons references were added to C++ in the first place. It also makes your code easier to understand if you don't have to pepper it with pointer dereferences.
This question already has answers here:
Difference Between Reference Sign After Data Type or Before Variable Name?
(3 answers)
Closed 7 years ago.
I'm trying to learn the basics of C++. The book I'm reading uses the following syntax:
func(int& x);
On the internet, I mostly see the following syntax:
func(int &x);
Both seem to do exactly the same. Is there any difference?
Literally no difference. Just a stylistic preference. The same is true of where you put the pointer.
See the answer to the Is int* p; right or is int *p; right? FAQ on Bjarne Stroustrup's website. It's for pointers, but what he writes equally holds for references:
Both are "right" in the sense that both are valid C and C++ and both
have exactly the same meaning. [...] The choice between int* p; and int *p; is not about right and wrong, but about style and emphasis.
I prefer int& x. This way the reference becomes part of the type, it's an "int reference" called x, instead of "int, reference of x"
I find that thinking of "int reference" as a discrete type makes it less confusing, but to the compiler it's the same thing.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ Reference, change the refered variable
I know that references in c++ are just pointers that get dereferenced for you when you use them. This question is about how to access the underlying pointer and change it.
Consider this code:
int x;
int& x_ref = x; //now equivalent to x
int* x_ptr = &x; //stores address of x
int* x_ref_ptr = &x_ref; //ALSO stores address of x
int&* x_ref_ptr_ref = ???; //what would this mean?
I'm trying to change where a reference points after initialization. I have no concern for type safety or proper practices. Does the c++ language have any tool to let me accomplish this?
There is no pointer to reference, it's ill-formed. A reference is an alias to an object. How would a pointer to an alias work?
Also, it's a feature of the language that a reference can't be reseated. A reseatable reference is a pointer.
This is not possible by design. By using a reference instead of a pointer, you decide to never change its target after declaration, with all entailing drawbacks and advantages (one of which is its "automatic dereferencing". Read the Wikipedia entry on references carefully.
You will need to switch to pointers.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
I got my head around pointers in C (the basics anyway) and started reading up on C++. The book I'm reading jumps straight into references, and looking in the index doesnt got on to pointers until later on.
In C, I thought if I wanted to do a pass by reference function I would have to use pointers as arguments,
e.g.
void swapAandB(int *A, int *B){
//do something
}
But the C++ book, decides to put references to the original variable into the function. e.g.
void swapAandB(int& A, int& B){
//do something
}
My C++ book hasn't explained why we don't use pointers as in C. So I'm a little confused. I guess my question is what's going on here?
References are and additional mechanism that C++ provides compared to C. Using pointers in C++ is perfectly legal, so you could still define your first function unmodified:
void swapAandB(int *A, int *B){
//do something
}
The main advantage that references offer over pointers is that it is not that easy to have the equivalent of a NULL pointer. But, references, both semantically and syntactically go well beyond this in shaping C++ features as a language. I think this will become clearer once you get more into the language. Anyway, you can try and read this paper about the difference between pointers and references.
You can use pointers as in C of course but references are objects aliases, so, the object exist, you don't need to check if their are valid. There are differences with pointers in their use:
void foo(Type * pointer)
{
if (pointer)
pointer->data_ = ....;
}
void foo(Type & reference)
{
reference.data_ = ....;
}
Type obj;
foo(&obj); // pointer syntax
foo(obj); // reference syntax
Besides, a reference always 'point' to the same object, so you will be sure always of using it correctly.
In this case pointers and references will behave the same way.
The only difference is how you call them:
int x, y;
swapAandB( &x, &y ); // here you pass the variables' addresses to the pointer function
swapAandB( x, y ); // here you pass the variables' reference to the reference function
The result is the same, the variables don't get copied, but rather referenced from within the functions, and any changes you apply to them inside the function will affect the variables in the calling scope.
As a rule:
Try to use references instead of pointers.
In some cases you need to use pointers:
polymorphism
you need to have something like a null pointer
you need to delete a variable later on
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Difference between pointer variable and reference variable in C++
I saw this simple code the other day, and I consider myself a beginner with pointers, although I have about a year and half experience with c++. Anyways...
Whats the difference between
int a = 0;
int &b = a;
and
int a = 0
int *p = &a;
Obviously, p holds the address of a, but b is a reference to a, meaning I can change the value of a with b. But I can also do the same thing with p. So what are advantages or disadvantages?
A reference must always be initialized
A reference can't be null
Once initialized, a reference can't be changed to be an alias of a different object.
I think it comes down to how you plan to use the variables afterwards in your program. Both statements appear to do the same thing (in this limited scope).
The first approach seems to be (in my opinion) poor programming practice since it may not be obvious later in the program that changing the value of b also changes the value of a. In the second, at least it is known that p is a pointer, so you should expect the side effects that come with changing the value to which it points.