Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Pointers Use Cases | Pointers Fundamentals
C++ Pointers and References

book
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.

cpp

main

copy
#include <iostream>

void increment(int num) { num++; }

int main()
{
int num = 5;
increment(num);
std::cout << "Original value: " << num << std::endl;
}
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.

cpp

main

copy
#include <iostream>

void increment(int* num) { (*num)++; }

int main()
{
int num = 5;
int* p_num = &num;

increment(p_num);
std::cout << "Original value: " << num << std::endl;
}
123456789101112
#include <iostream> void increment(int* num) { (*num)++; } int main() { int num = 5; int* p_num = &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

  1. Create a function that swaps values of two variables.
  2. Call this function.
  3. Output the values of variables after the swap.

Рішення

cpp

solution

#include <iostream>

void swap(int* a, int* b)
{
int temporary = *a;
*a = *b;
*b = temporary;
}


int main()
{
int first = 100;
int second = 0;
swap(&first, &second);
std::cout << first << ' ' << second;
}

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 4
#include <iostream>

void swap(int _ p_first, int _ p_second)
{
int temporary = _ ___;
* ___ = _ ___;
_ ___ = temporary;
}


int main()
{
int first = 100;
int second = 0;
swap(___, ___);
std::cout << first << ' ' << second;
}
toggle bottom row
We use cookies to make your experience better!
some-alt