-1

I have some issues getting my head around the idea of pointers. I know what they do in theory, but i have a problem understanding what they can actually be capable of. The basic exercises that i have seen are a bit vague in my opinion because they can be done without the actual subject. For example swapping two number, either by reference or by address.

#include <iostream>
using namespace std;

int main()
{
int a = 45, b = 35;
cout << "Before Swap\n";
cout << "a = " << a << " b = " << b << "\n";

int z = a;
a = b;
b = z;

cout << "After Swap with pass by reference\n";
cout << "a = " << a << " b = " << b << "\n";
} 
//copied an example i saw online with pointers and modified it to get the 
same result without needing them
Vlad
  • 23
  • 5
  • 1
    The code you've shown involves neither pointers nor references. – François Andrieux Jan 31 '19 at 19:05
  • Some problems can be solved without pointers. Some can't. I think teachers often contrive simple situations that don't really need pointers just to demonstrate them without having to deal with the more complex situations in which they become necessary. – Galik Jan 31 '19 at 19:07

2 Answers2

2

One example on when using pointers could be better (assuming this is some sort of school context) would be if you want to make a function to swap the numbers instead of rewriting your code a lot.

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

If you tried using integers in the function instead of pointers, it'd swap the values locally, and not swap the variables in a greater context. What you could do to achieve the same results is use references instead (ie int &a, int &b), so you don't really need to use pointers, and in this example they aren't particularly useful.

Pragmatically, std::swap()is much more useful in modern c++, but the example above might be why the online tutorial uses pointers.

Pointers can be useful in other contexts, but I don't know if that's within the scope of your question, just perhaps what the tutorial was trying to achieve by using pointers.

Daniel
  • 854
  • 7
  • 18
  • 1
    To better understand what this answer is getting at, here is some extra reading: [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) – user4581301 Jan 31 '19 at 22:09
0

Use the std::swap() method for swaping. It is more efficient.

For your understanding if we write a function which swaps two values so we have to pass the values by reference and not by value.

same is the case with pointers.some time we need to swap value by pointers.

So if we pass values to this function from the main it will swap it.

void swap(int&,int&); 

But here it won't work if we pass values to this function from the main.

void swap(int,int);
Hamza.S
  • 1,319
  • 9
  • 18