There can still be some common properties among references in different programming languages in general, but let's leave it for some other questions in SO. A reference is not another name given to some memory. It's a immutable pointer that is automatically de-referenced on usage. Basically it boils down to:. A reference to a pointer provides a cleaner syntax to modify the pointer. Look at this example:. And consider the C version of the above program.
In C you have to use pointer to pointer multiple indirection , and it leads to confusion and the program may look complicated. There is one fundamental difference between pointers and references that I didn't see anyone had mentioned: references enable pass-by-reference semantics in function arguments. Pointers, although it is not visible at first do not: they only provide pass-by-value semantics.
This has been very nicely described in this article. Null pointers can be used as a sentinel value, often a cheap way to avoid function overloading or use of a bool. At the risk of adding to confusion, I want to throw in some input, I'm sure it mostly depends on how the compiler implements references, but in the case of gcc the idea that a reference can only point to a variable on the stack is not actually correct, take this for example:.
If you notice even the memory addresses are exactly the same, meaning the reference is successfully pointing to a variable on the heap!
Now if you really want to get freaky, this also works:. Well, obviously it compiles fine, but causes a segmentation fault at runtime because it's no longer pointing at a valid variable, we essentially have a broken reference that still exists until it falls out of scope , but is useless. In other words, a reference is nothing but a pointer that has the pointer mechanics abstracted away, making it safer and easier to use no accidental pointer math, no mixing up '.
Now regardless of how a compiler handles references, it will always have some kind of pointer under the hood, because a reference must refer to a specific variable at a specific memory address for it to work as expected, there is no getting around this hence the term 'reference'.
The only major rule that's important to remember with references is that they must be defined at the time of declaration with the exception of a reference in a header, in that case it must be defined in the constructor, after the object it's contained in is constructed it's too late to define it.
Remember, my examples above are just that, examples demonstrating what a reference is, you would never want to use a reference in those ways!
For proper usage of a reference there are plenty of answers on here already that hit the nail on the head. Another difference is that you can have pointers to a void type and it means pointer to anything but references to void are forbidden. I can't say I'm really happy with this particular difference.
I would much prefer it would be allowed with the meaning reference to anything with an address and otherwise the same behavior for references.
It would allow to define some equivalents of C library functions like memcpy using references. Also, a reference that is a parameter to a function that is inlined may be handled differently than a pointer. Many compilers when inlining the pointer version one will actually force a write to memory we are taking the address explicitly.
However, they will leave the reference in a register which is more optimal. Of course, for functions that are not inlined the pointer and reference generate the same code and it's always better to pass intrinsics by value than by reference if they are not modified and returned by the function. This program might help in comprehending the answer of the question. This is a simple program of a reference "j" and a pointer "ptr" pointing to variable "x".
Unlike the pointers, references are syntactically equivalent to the object they refer to, i. Returning the character by reference allows user-defined classes to have the same notation. Copy constructors. Syntactically it makes sense to pass objects to copy constructors, and not pointers to objects.
But there is just no way for a copy constructor to take an object by value - it would result in a recursive call to the same copy constructor. This leaves references as the only option here. Operator overloads. This also works for regular overloaded functions. There is a very important non-technical difference between pointers and references: An argument passed to a function by pointer is much more visible than an argument passed to a function by non-const reference.
For example:. Some argue that this is such a useful feature when reading code, that pointer parameters should always be used for modifiable parameters rather than non- const references, even if the function never expects a nullptr.
That is, those people argue that function signatures like fn3 above should not be allowed. A pointer can be initialized to 0 and a reference not. In fact, a reference must also refer to an object, but a pointer can be the null pointer:. In fact to do it properly, we must have declared and defined an object at the first then we can make a reference to that object, so the correct implementation of the previous code will be:.
Another important point is that is we can make the declaration of the pointer without initialization however no such thing can be done in case of reference which must make a reference always to variable or object.
However such use of a pointer is risky so generally we check if the pointer is actually is pointing to something or not. In case of a reference no such check is necessary, because we know already that referencing to an object during declaration is mandatory. Another point: When we have a template like an STL template such kind of a class template will always return a reference, not a pointer, to make easy reading or assigning new value using operator []:.
Even though pointers and references are implemented in much the same way "under-the-hood," the compiler treats them differently, resulting in all the differences described above. A recent article I wrote that goes into much greater detail than I can show here and should be very helpful for this question, especially about how things happen in memory:. Basically references were introduced to allow support for operators overloading as I had read in some very old book. As somebody stated in this thread - pointer can be set to 0 or whatever value you want.
It is an error to dereference null pointer. But actually the pointer may contain a value that doesn't point to some correct memory location. References in their turn try not to allow a user to initialize a reference to something that cannot be referenced due to the fact that you always provide rvalue of correct type to it.
Although there are a lot of ways to make reference variable be initialized to a wrong memory location - it is better for you not to dig this deep into details. On machine level both pointer and reference work uniformly - via pointers.
Let's say in essential references are syntactic sugar. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Ask Question. Asked 13 years, 2 months ago. Active 1 month ago. Viewed 1. I know references are syntactic sugar, so code is easier to read and write. But what is the difference between a pointer variable and a reference variable? Improve this question.
Silence 79 1 1 silver badge 7 7 bronze badges. Only malformed code can create a NULL reference and its behavior is undefined. References on the other hand are never objects, only variables. Reference can indeed point to NULL. I like how the very first sentence is a total fallacy. References have their own semantics. Show 20 more comments. Active Oldest Votes. References cannot be put into an array, whereas pointers can be Mentioned by user litb Const references can be bound to temporaries.
Improve this answer. For example, you can't test if a reference is NULL e. Number 2 is not true. A references is not simply "another name for the same variable. They exist independently from the variables they point to.
Brian, the stack is not relevant. References and pointers do not have to take space on the stack. They can both be allocated on the heap. Brian, the fact that a variable in this case a pointer or reference requires space does not mean it requires space on the stack.
Pointers and references may not only point to the heap, they may actually be allocated on the heap. Show 41 more comments. Peter Mortensen 29k 21 21 gold badges 97 97 silver badges bronze badges.
Christoph Christoph k 36 36 gold badges silver badges bronze badges. Consider a member function that returns a reference to a class member variable: that's safe and should not be forbidden by the compiler. Then a caller that has an automatic instance of that class, calls that member function, and returns the reference. Presto: dangling reference. And yes, it's going to cause trouble, kriss: that's my point.
Many people claim that an advantage of references over pointers is that references are always valid, but it just isn't so. Anyway, I was just providing a counter-example to your statement that you can only get an invalid reference by dereferencing an invalid pointer. Christoph is correct -- references are not any safer than pointers, a program which uses references exclusively can still break type safety.
References are not a kind of pointer. They are a new name for an existing object. Show 12 more comments. Matt Price Matt Price Then to be really pedantic you need to look at the Return Value Optimization whereby the compiler is allowed to elide the copy construction in the first case. Since it is a reference, no slicing will take place in between.
AhmadMushtaq: The key use of this is derived classes. Show 4 more comments. Update: now that I think about it some more, there is an important difference. A const pointer's target can be replaced by taking its address and using a const cast. A reference's target cannot be replaced in any way short of UB. This should permit the compiler to do more optimization on a reference. I think this is the best answer by far. Others talk about references and pointers like they are different beasts and then lay out how they differ in behavior.
It doesn't make things any easier imho. See stackoverflow. Trying to change either the referent of a reference or the value of a const pointer or any const scalar is equality illegal. The difference here is UB versus literally impossible. Not impossible, harder, you can just access the memory area of the pointer that is modeling that reference and change its content.
That can certainly be done. Show 1 more comment. Contrary to popular opinion, it is possible to have a reference that is NULL. My example above is short and contrived. Here's a more real-world example. Mark Ransom Mark Ransom k 40 40 gold badges silver badges bronze badges. The code in question contains undefined behavior.
Technically, you cannot do anything with a null pointer except set it, and compare it. Once your program invokes undefined behavior, it can do anything, including appearing to work correctly until you are giving a demo to the big boss.
The description is erroneous. This code might or might not create a reference that is NULL. Its behavior is undefined. It might create a perfectly valid reference. It might fail to create any reference at all. David Schwartz, if I were talking about the way things had to work according to the standard, you'd be correct.
But that's not what I'm talking about - I'm talking about actual observed behavior with a very popular compiler, and extrapolating based on my knowledge of typical compilers and CPU architectures to what will probably happen.
If you believe references to be superior to pointers because they're safer and don't consider that references can be bad, you'll be stumped by a simple problem someday just as I was.
Dereferencing a null pointer is wrong. Any program that does that, even to initialize a reference is wrong. If you are initializing a reference from a pointer you should always check that the pointer is valid. Even if this succeeds the underlying object may be deleted at any time leaving the reference to refer to non-existing object, right? What you are saying is good stuff.
I think the real issue here is that reference does NOT need to be checked for "nullness" when you see one and pointer should be, at minimum, asserted. Show 13 more comments. The reference variable is assigned the variable a, i. Now, when we assign another value to b, we modify the value of a. Hence, it can be said that the changes done to a reference variable will also occur in variable referred by that reference variable. The most important point is that the reference variable must be initialized at the time of its creation.
Once the reference variable is initialized with a variable, it can not be reinitialized to refer an another variable. The moment you assign a value to a reference variable, you assign that value to a variable that a reference variable points to.
Arithmetic can not be performed on a reference variable. Note Java does not support pointers. The pointer and reference both are used to point or refer another variable. But both differ in their usage and implementation. Your email address will not be published. Key Differences Between Pointer and Reference Reference is like creating an another name to refer a variable so that it can be refered with different names.
On the other hand, a pointer is simply a memory address of a variable. Please mail your requirement at [email protected] Duration: 1 week to 2 week. Value of 'a' is Now value of 'a' is The address of 'a' variable is : 0x7fffe7e44 The address of 'i' variable is : 0x7fffe7e4.
The memory address of p variable is :0x7ffcc5cb8 The memory address of k variable is :0x7ffcc5cb4. Reinforcement Learning. R Programming. React Native. Python Design Patterns. Python Pillow. Python Turtle. Verbal Ability. Interview Questions. Company Questions. Artificial Intelligence.
Cloud Computing. Data Science. Angular 7. Machine Learning. Data Structures. Operating System. Computer Network. Compiler Design. Computer Organization.
Discrete Mathematics. Ethical Hacking.
0コメント