Pointers and References in C++
Last Updated :
11 Jan, 2024
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable.
Pointers in C++
Pointers in C++ are a symbolic representation of addresses. They enable programs to simulate call-by-reference and create and manipulate dynamic data structures. Pointers store the address of variables or a memory location.
Syntax
datatype *var_name;
for example, int *ptr; //ptr points to an address that holds int data.
Example of Pointers in C++
The below program demonstrates the use of pointers in C++.
C++
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int * myptr;
myptr = &x;
cout << "Value of x is: " ;
cout << x << endl;
cout << "Address stored in myptr is: " ;
cout << myptr << endl;
cout << "Value of x using *myptr is: " ;
cout << *myptr << endl;
return 0;
}
|
Output
Value of x is: 10
Address stored in myptr is: 0x7ffd2b32c7f4
Value of x using *myptr is: 10
Explanation: The above program declares an integer variable ‘x’ initialized with value 10 and a pointer variable named ‘myptr’. The memory address of x is assigned to myptr. Then it prints the value of x, the address stored in myptr, and the value of x obtained by dereferencing the pointer myptr.
To know more about Pointers, how it works and its mathematical background refer to Pointers in C++.
Application of Pointers in C++
Following are the Applications of Pointers in C++:
- To pass arguments by reference: Passing by reference serves two purposes
- For accessing array elements: The Compiler internally uses pointers to access array elements.
- To return multiple values: For example in returning square and the square root of numbers.
- Dynamic memory allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, that it is not deleted until we explicitly delete it.
- To implement data structures.
- To do system-level programming where memory addresses are useful.
Features and Use of Pointers in C++
The Pointers have a few important features and uses like it saves memory space, they are used to allocate memory dynamically, it is used for file handling, etc. Pointers store the address of variables or a memory location.
Example: pointer “ptr” holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through “ptr”.
int *ptr;
‘this’ Pointer in C++
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name). Even if only one member of each function exists which is used by multiple objects, the compiler supplies an implicit pointer along with the names of the functions as ‘this’.
Declaration:
this->x = x;
References in C++
When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration. There are 3 ways to pass C++ arguments to a function:
Example of References in C++
The below program demonstrates the use of references in C++.
C++
#include <iostream>
using namespace std;
int main()
{
int y = 10;
int & myref = y;
y = 30;
cout << "value of y is " << y << endl;
cout << "value of myref after change in value of y is: "
<< myref << '\n' ;
return 0;
}
|
Output
value of y is 30
value of myref after change in value of y is: 30
Explanation: The above program demonstrates the use of references. First, it declares an integer variable ‘y’ and then creates reference ‘myref’ which is an alias to y. Changing the value of y also changes the value of myref which can be seen after printing values of both y and myref.
Pointers vs References
Pointers vs References in C++: This article lays the proper ground for differences between Pointer and references. Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain.
Despite the above similarities, there are the following differences between references and pointers.
Note A pointer can be declared as void but a reference can never be void.For example:
int a = 10;
void*aa = &a;. //it is valid
void &ar = a; // it is not valid
- References are less powerful than pointers
- Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
- References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
- A reference must be initialized when declared. There is no such restriction with pointers
- Passing by pointer Vs Passing by Reference in C++: In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So what should be preferred and why?
- Passing Reference to a Pointer in C++: In this article let’s compare the usage of a “pointer to pointer” VS “Reference to pointer” in some cases.
Similar Reads
C++ Tutorial | Learn C++ Programming
C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc. Why Learn C++?C++
5 min read
Setting up C++ Development Environment
C++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Writing First C++ Program - Hello World Example
The "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
C++ Variables
In C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution. Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variabl
5 min read
C++ Data Types
Data types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory. C++ supports a wide variety of data ty
8 min read
Operators in C++
In C++, an operator is a symbol that operates on a value to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a;
9 min read
Basic Input / Output in C++
In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams. Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of byte
5 min read
Decision Making in C++
Decision Making in C (if , if..else, Nested if, if-else-if )
In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
8 min read
C++ if Statement
The C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int
3 min read
C++ if else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
4 min read
C++ if else if Ladder
In C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
3 min read
C++ Nested if-else Statement
Nested if-else statements are those statements in which there is an if statement inside another if else. We use nested if-else statements when we want to implement multilayer conditions (condition inside the condition inside the condition and so on). C++ allows any number of nesting levels. Let's ta
3 min read
Switch Statement in C++
In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is an alternative to the long if-else-if ladder which provides an easy way to execute different parts of code based on the value of the e
6 min read
Jump statements in C++
Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function. In C++, there is four jump statement: Table of Content continue Statementbreak Statementreturn Statementgot
4 min read
C++ Loops
C++ Loops
In C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown. [GFGTABS] C++ #include <iostream> using namesp
8 min read
for Loop in C++
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand. Let's take a look at an example: [GFGTABS] C++ #include <bit
6 min read
C++ While Loop
In C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while Loop
In C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
Range-Based for Loop in C++
In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops. Let's take
3 min read
Functions in C++
A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read