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 bReferences 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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate 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() functionAll lessons in C++ Pointers
2Pointers & References
Pointers as ParametersReferences - &References as ParametersPointers vs References