Menu
Coddy logo textTech

Pointers vs References

Lesson 10 of 14 in Coddy's C++ Pointers course.

As we discussed, in C++ we can use pointers and references to access other variables and their values, but there are a few key differences between them

Pointers can be null, or can point to nothing, and after we declare them, later we can change what they point to

int a = 10, b = 20;
int *ptr; // Points to nothing

ptr = &a; // Points to a
ptr = &b; // Points to b

References represent aliases for another variable. They can't be uninitialized (null), they can't refer to nothing. They must be initialized when declare and can't be re-referred

int a = 10;
    
// Not allowed
int &ref;
    
// Allowed
int &refA = a;

There are a few differences between pointers and references, we use both for different tasks, but it's important to know what you can and can't do with the one and the other.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a function swapP taking two integers as parameters and use pointers to swap the values of the given numbers, and create a function swapR where you do the same but use references and not pointers

Note: Do NOT write the <i>main()</i> function

Try it yourself

#include <iostream>

using namespace std;

void swapP() {}

void swapR() {}


// Do NOT write the main() function

All lessons in C++ Pointers