-2
#include <iostream>

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

int main() {
    int alpha = 5;
    int beta = 34;

    swap (alpha,beta);

    std::cout << alpha << std::endl;
    std::cout << beta << std::endl;

    int *ab = new int();
    *ab = 34;
    int *cd = new int();
    *cd =64;

    swap(ab,cd);

    std::cout << *ab << std::endl;
    std::cout << *cd << std::endl;
}

First Question: How am I able to pass values to a function which has pointers as passing parameters.

Second Question: How is it able to swap. It swaps the pointers. But when it comes out shouldn't the values of alpha and beta still remain same.

Third Question: Why doesn't the function work when I pass pointers but works when I pass regular variables.

Fourth Question: In the function void swap(int *a, int* b) are int *a and int *b references?

Alexander.
  • 117
  • 1

2 Answers2

4

And that would serve the best examples for why we should not include namespace std at global level…

swap (alpha,beta);

would call std::swap rather than your own swap.

Third Question: Why doesn't the function work when I pass pointers but works when I pass regular variables

Because your swap isn't properly written. It should be:

void swap (int *a, int *b) {
    // Preferably you should also check if pointers are not NULL.
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

Fourth Question: In the function void swap(int *a, int* b) are int *a and int *b references?

The syntax of reference is:

void swap ( int& a, int& b );

So no, they aren't. They are pointers.

ravi
  • 10,994
  • 1
  • 18
  • 36
1

First of all your swap function is wrong. I suppose you want to swap not pointers themselves but the objects pointed to by the pointers. It should be defined as

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

and it can be called like

swap ( &alpha, &beta );

and

swap( ab, cd );

In this function parameters a and b are pointers. If you want to use references as the parameters then the function will look like

void swap( int &a, int &b )
{
   int tmp = a;
   a = b;
   b = tmp;
}

and can be called like

swap ( alpha, beta );

and

swap( *ab, *cd );

If you want to swap separatly pointers and objects pointed to by pointers then either you need to define two overloaded functions or one template function like standard C++ function std::swap.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335