Pointers Use Cases
When you pass a variable to a function, you're essentially passing its value. This means the function receives a copy of the data. Any modifications made inside the function do not affect the original variable.
main.cpp
12345678910#include <iostream> void increment(int num) { num++; } int main() { int num = 5; increment(num); std::cout << "Original value: " << num << std::endl; }
We can use pointers to enable a function to alter the original variable. This involves passing a memory address as an argument instead of the actual value.
main.cpp
123456789101112#include <iostream> void increment(int* num) { (*num)++; } int main() { int num = 5; int* p_num = # increment(p_num); std::cout << "Original value: " << num << std::endl; }
Note
You can bypass the creation of a pointer to a variable and instead directly use the address-of operator when passing a variable.
Swipe to start coding
- Create a function that swaps values of two variables.
- Call this function.
- Output the values of variables after the swap.
Løsning
solution.cpp
Takk for tilbakemeldingene dine!
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 5.88
Pointers Use Cases
Sveip for å vise menyen
When you pass a variable to a function, you're essentially passing its value. This means the function receives a copy of the data. Any modifications made inside the function do not affect the original variable.
main.cpp
12345678910#include <iostream> void increment(int num) { num++; } int main() { int num = 5; increment(num); std::cout << "Original value: " << num << std::endl; }
We can use pointers to enable a function to alter the original variable. This involves passing a memory address as an argument instead of the actual value.
main.cpp
123456789101112#include <iostream> void increment(int* num) { (*num)++; } int main() { int num = 5; int* p_num = # increment(p_num); std::cout << "Original value: " << num << std::endl; }
Note
You can bypass the creation of a pointer to a variable and instead directly use the address-of operator when passing a variable.
Swipe to start coding
- Create a function that swaps values of two variables.
- Call this function.
- Output the values of variables after the swap.
Løsning
solution.cpp
Takk for tilbakemeldingene dine!
Awesome!
Completion rate improved to 5.88single