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
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:
Closed 11 years ago.
Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
How to pass objects to functions in C++?
I am learning about reference parameters and got the following question:
What is the difference between this:
void B(int* worthRef) {
*worthRef += 1;
}
int main() {
int netWorth = 55;
B(&netWorth);
return 0;
}
And this:
void B(int &worthRef) {
worthRef += 1;
}
int main() {
int netWorth = 55;
B(netWorth);
return 0;
}
The first one (int *) passes a pointer-to-integer by value; the second (int &) passes an integer by reference. Both methods can be used to implement abstract "reference semantics", but in C++ you should use actual references when possible.
When you use pointers to implement reference semantics, you pass by value a pointer to the object that you want to refer to, and you dereference the pointer to obtain the actual object reference. In C, where you have no references in the language, that's the only way to implement reference semantics, but in C++ you have actual reference types in the language for this purpose.
Note that passing a pointer can be used a little differently from a reference, since you can pass a null pointer to convey additional semantics, and you can also modify the pointer variable (e.g. for using the local copy of the pointer in the callee scope to traverse an array).
But in a nutshell: Use references. Don't use naked pointers in C++. (To implement reference semantics, you use references, and to implement whatever else naked pointers can be (ab)used for, use the appropriate higher-level idiom.) The fundamental problem with naked pointers is that they convey no ownership semantics, and C++ has many far better tools to write maintainable, local and self-documenting code.
Here you are passing the address of the int:
void B(int* worthRef) {
*worthRef += 1;
}
The parameter is a pointer. The address passed may be 0 (or NULL). Also used in C. The pointer may altered within B: ++worthRef - why you would prefer that...
Here, the implementation takes the address of the parameter:
void B(int &worthRef) {
worthRef += 1;
}
The parameter is a C++ reference. The address passed must not be 0, and may not be altered (of course, what it refers to may be altered if not const, as seen in your example). This is the default written style in most C++ circles. Mechanically, a reference is a bit of syntactic sugar, but it is absolutely useful to convey intent and offer guarantees.
Stylistically, some people prefer the former for parameters which may mutate. I use the latter wherever possible (and legal) -- it's more conventional for C++.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
Are there benefits of passing by pointer over passing by reference in C++?
In both cases, I achieved the result.
So when is one preferred over the other? What are the reasons we use one over the other?
#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x=*y;
*y=z;
}
void swap(int& x, int& y)
{
int z = x;
x=y;
y=z;
}
int main()
{
int a = 45;
int b = 35;
cout<<"Before Swap\n";
cout<<"a="<<a<<" b="<<b<<"\n";
swap(&a,&b);
cout<<"After Swap with pass by pointer\n";
cout<<"a="<<a<<" b="<<b<<"\n";
swap(a,b);
cout<<"After Swap with pass by reference\n";
cout<<"a="<<a<<" b="<<b<<"\n";
}
Output
Before Swap
a=45 b=35
After Swap with pass by pointer
a=35 b=45
After Swap with pass by reference
a=45 b=35
A reference is semantically the following:
T& <=> *(T * const)
const T& <=> *(T const * const)
T&& <=> [no C equivalent] (C++11)
As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.
An advantage over pointers is that you need explicit casting in order to pass NULL.
It's still possible, though.
Of the compilers I've tested, none emit a warning for the following:
int* p() {
return 0;
}
void x(int& y) {
y = 1;
}
int main() {
x(*p());
}
In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.
Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.
Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.
References have a couple more advantages compared to pointers (e. g. they can't be NULL, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.
Pass by pointer is the only way you could pass "by reference" in C, so you still see it used quite a bit.
The NULL pointer is a handy convention for saying a parameter is unused or not valid, so use a pointer in that case.
References can't be updated once they're set, so use a pointer if you ever need to reassign it.
Prefer a reference in every case where there isn't a good reason not to. Make it const if you can.
Here is a good article on the matter - "Use references when you can, and pointers when you have to."
Use references all the time and pointers only when you have to refer to NULL which reference cannot refer.
See this FAQ :
http://www.parashift.com/c++-faq-lite/references.html#faq-8.6
I'm new to the C++ community, and just have a quick question about how C++ passes variables by reference to functions.
When you want to pass a variable by reference in C++, you add an & to whatever argument you want to pass by reference. How come when you assign a value to a variable that is being passed by reference why do you say variable = value; instead of saying *variable = value?
void add_five_to_variable(int &value) {
// If passing by reference uses pointers,
// then why wouldn't you say *value += 5?
// Or does C++ do some behind the scene stuff here?
value += 5;
}
int main() {
int i = 1;
add_five_to_variable(i);
cout << i << endl; // i = 6
return 0;
}
If C++ is using pointers to do this with behind the scenes magic, why aren't dereferences needed like with pointers? Any insight would be much appreciated.
When you write,
int *p = ...;
*p = 3;
That is syntax for assigning 3 to the object referred to by the pointer p. When you write,
int &r = ...;
r = 3;
That is syntax for assigning 3 to the object referred to by the reference r. The syntax and the implementation are different. References are implemented using pointers (except when they're optimized out), but the syntax is different.
So you could say that the dereferencing happens automatically, when needed.
C++ uses pointers behind the scenes but hides all that complication from you. Passing by reference also enables you to avoid all the problems asssoicated with invalid pointers.
When you pass an object to a function by reference, you manipulate the object directly in the function, without referring to its address like with pointers. Thus, when manipulating this variable, you don't want to dereference it with the *variable syntax. This is good practice to pass objects by reference because:
A reference can't be redefined to point to another object
It can't be null. you have to pass a valid object of that type to the function
How the compiler achieves the "pass by reference" is not really relevant in your case.
The article in Wikipedia is a good ressource.
There are two questions in one, it seems:
one question is about syntax: the difference between pointer and reference
the other is about mechanics and implementation: the in-memory representation of a reference
Let's address the two separately.
Syntax of references and pointers
A pointer is, conceptually, a "sign" (as road sign) toward an object. It allows 2 kind of actions:
actions on the pointee (or object pointed to)
actions on the pointer itself
The operator* and operator-> allow you to access the pointee, to differenciate it from your accesses to the pointer itself.
A reference is not a "sign", it's an alias. For the duration of its life, come hell or high water, it will point to the same object, nothing you can do about it. Therefore, since you cannot access the reference itself, there is no point it bothering you with weird syntax * or ->. Ironically, not using weird syntax is called syntactic sugar.
Mechanics of a reference
The C++ Standard is silent on the implementation of references, it merely hints that if the compiler can it is allowed to remove them. For example, in the following case:
int main() {
int a = 0;
int& b = a;
b = 1;
return b;
}
A good compiler will realize that b is just a proxy for a, no room for doubts, and thus simply directly access a and optimize b out.
As you guessed, a likely representation of a reference is (under the hood) a pointer, but do not let it bother you, it does not affect the syntax or semantics. It does mean however that a number of woes of pointers (like access to objects that have been deleted for example) also affect references.
The explicit dereference is not required by design - that's for convenience. When you use . on a reference the compiler emits code necessary to access the real object - this will often include dereferencing a pointer, but that's done without requiring an explicit dereference in your code.
I was studying pointers references and came across different ways to feed in parameters. Can someone explain what each one actually means?
I think the first one is simple, it's that x is a copy of the parameter fed in so another variable is created on the stack.
As for the others I'm clueless.
void doSomething1(int x){
//code
}
void doSomething2(int *x){
//code
}
void doSomething3(int &x){
//code
}
void doSomething3(int const &x){
//code
}
I also see stuff like this when variables are declared. I don't understand the differences between them. I know that the first one will put 100 into the variable y on the stack. It won't create a new address or anything.
//example 1
int y = 100;
//example 2
int *y = 100;
//Example 3: epic confusion!
int *y = &z;
Question 1: How do I use these methods? When is it most appropriate?
Question 2: When do I declare variables in that way?
Examples would be great.
P.S. this is one the main reasons I didn't learn C++ as Java just has garbage collection. But now I have to get into C++.
//example 1
int y = 100;
//example 2
int *y = 100;
//Example 3: epic confusion!
int *y = &z;
I think the problem for most students is that in C++ both & and * have different meanings, depending on the context in which they are used.
If either of them appears after a type within an object declaration (T* or T&), they are type modifiers and change the type from plain T to a reference to a T (T&) or a pointer to a T (T*).
If they appear in front of an object (&obj or *obj), they are unary prefix operators invoked on the object. The prefix & returns the address of the object it is invoked for, * dereferences a pointer, iterator etc., yielding the value it references.
It doesn't help against confusion that the type modifiers apply to the object being declared, not the type. That is, T* a, b; defines a T* named a and a plain T named b, which is why many people prefer to write T *a, b; instead (note the placement of the type-modifying * adjacent the object being defined, instead of the type modified).
Also unhelpful is that the term "reference" is overloaded. For one thing it means a syntactic construct, as in T&. But there's also the broader meaning of a "reference" being something that refers to something else. In this sense, both a pointer T* and a reference (other meaning T&) are references, in that they reference some object. That comes into play when someone says that "a pointer references some object" or that a pointer is "dereferenced".
So in your specific cases, #1 defines a plain int, #2 defines a pointer to an int and initializes it with the address 100 (whatever lives there is probably best left untouched ), and #3 defines another pointer and initializes it with the address of an object z (necessarily an int, too).
A for how to pass objects to functions in C++, here is an old answer from me to that.
From Scott Myers - More Effective C++ -> 1
First, recognize that there is no such thing as a null reference. A reference must always refer to some object.Because a reference must refer to an object, C++ requires that references be initialized.
Pointers are subject to no such restriction. The fact that there is no such thing as a null reference implies that it can be more efficient to use references than to use pointers. That's because there's no need to test the validity of a reference before using it.
Another important difference between pointers and references is that pointers may be reassigned to refer to different objects. A reference, however, always refers to the object with which it is initialized
In general, you should use a pointer whenever you need to take into account the possibility that there's nothing to refer to (in which case you can set the pointer to null) or whenever you need to be able to refer to different things at different times (in which case you can change where the pointer points). You should use a reference whenever you know there will always be an object to refer to and you also know that once you're referring to that object, you'll never want to refer to anything else.
References, then, are the feature of choice when you know you have something to refer to, when you'll never want to refer to anything else, and when implementing operators whose syntactic requirements make the use of pointers undesirable. In all other cases, stick with pointers.
Read S.Lippmann's C++ Premier or any other good C++ book.
As for passing the parameters, generally when copying is cheap we pass by value. For mandatory out parameters we use references, for optional out parameters - pointers, for input parameters where copying is costly, we pass by const references
Thats really complicated topic. Please read here: http://www.goingware.com/tips/parameters/.
Also Scott Meiers "Effective C++" is a top book on such things.
void doSomething1(int x){
//code
}
This one pass the variable by value, whatever happens inside the function, the original variable doesn't change
void doSomething2(int *x){
//code
}
Here you pass a variable of type pointer to integer. So when accessing the number you should use *x for the value or x for the address
void doSomething3(int &x){
//code
}
Here is like the first one, but whatever happens inside the function, the original variable will be changed as well
int y = 100;
normal integer
//example 2
int *y = 100;
pointer to address 100
//Example 3: epic confusion!
int *y = &z;
pointer to the address of z
void doSomething1(int x){
//code
}
void doSomething2(int *x){
//code
}
void doSomething3(int &x){
//code
}
And i am really getting confused between them?
The first is using pass-by-value and the argument to the function will retain its original value after the call.
The later two are using pass-by-reference. Essentially they are two ways of achieving the same thing. The argument is not guarenteed to retain its original value after the call.
Most programmers prefer to pass large objects by const reference to improve the performance of their code and provide a constraint that the value will not change. This ensures the copy constructor is not called.
Your confusion might be due to the '&' operator having two meanings. The one you seem to be familiar with is the 'reference operator'. It is also used as the 'address operator'. In the example you give you are taking the address of z.
A good book to check out that covers all of this in detail is 'Accelerated C++' by Andrew Koening.
The best time to use those methods is when it's more efficient to pass around references as opposed to entire objects. Sometimes, some data structure operations are also faster using references (inserting into a linked list for example). The best way to understand pointers is to read about them and then write programs to use them (and compare them to their pass-by-value counterparts).
And for the record, knowledge of pointers makes you considerably more valuable in the workplace. (all too often, C++ programmers are the "mystics" of the office, with knowledge of how those magical boxes under the desks process code /semi-sarcasm)