This gist explains how the & operator works in C++, if you don't know how it is used and/or you are new to C++ you are in the right place
Starting off, the & operator in C++ is one of the most versatile operators and can have different meanings depending on the context in which it is used. This operator is essential for working with pointers, references and bitwise operations. In this guide, we will explore the three main uses of the & operator
This operator has 3 main uses:
- 1. Address-of Operator: Returns the memory address or pointer of a variable.
- 2. Reference Operator: Creates an alias (reference) for an existing variable.
- 3. Bitwise AND Operator: Performs a bitwise AND operation between two values.
Now we will see practical examples for each case, so that you fully understand how and when to use the & operator in your C++ code and when not to use it.
The first use of this operator is to get the address or pointer of a variable.
When we expect to pass a pointer to a variable that is not a pointer, the following will be necessary:
Example of assignment to an automatic variable to a pointer variable
Passing the value of a classic variable into a pointer without the & operator:
int x;
int* ptr = x // This is wrong and will generate a compilation errorIn this case, the code will not compile because x is an automatic variable (allocated on the stack) and stores a value of type int, while ptr is a pointer of type int*. You cannot directly assign an int to an int* without using the & operator.
Using the & operator to get the address of the variable:
int x;
int* ptr = &x // Now the code is correctHere, the & operator is used to get the address of x, which is then assigned to the pointer ptr. This works because &x returns a pointer to x (of type int*), which matches the type of ptr.
If x is already a pointer, the & operator is not needed:
In case the same variable x is already a pointer the & operator will not be necessary
int* x;
int* ptr = x // Here the & operator is not needed since x is already a pointerIn this case, x is already a pointer (of type int*), so you can directly assign it to ptr without using the & operator. This is because x already holds an address, and no additional operation is needed to obtain it.
Key Points:
- 1. Auto variables (located on the stack) are not pointers, so you cannot assign them directly to a pointer variable.
- 2. The
&operator is used to get the address of a variable, which can then be assigned to a pointer. - 3. If the variable is already a pointer, you do not need the & operator to assign it to another pointer.