1

I'm so new to c++, and i've just started doing pointers so when i'm using call by reference using pointers one thing i cant understand when i'm passing the addresses of the values , it works as it should be

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

int main(){
    int x=5 , y=10;
    swap(&x , &y);
    std::cout<<"The value of x is "<<x<<std::endl;
    std::cout<<"The value of y is "<<y<<std::endl;
}

but when i'm passing the values not the addresses it still works how?

int main(){
    int x=5 , y=10;
    swap(x , y);
    std::cout<<"The value of x is "<<x<<std::endl;
    std::cout<<"The value of y is "<<y<<std::endl;
}
py300
  • 51
  • 1
  • 1
    Next time round, do paste up the `#include`s too; actually the whole program, abridged to demonstrate the issue. Then we can be more certain about the answer. – Bathsheba Oct 06 '22 at 08:55

1 Answers1

5

This shouldn't compile, you can't pass an int to an int*. What likely happened is, you have a

using namespace std;

statement at the start, and swap(x, y) is actually calling std::swap. Get rid of the using statement and it should correctly fail to compile.


There are many pitfalls that come by using the namespace, read more about it on Why is "using namespace std;" considered bad practice?

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
  • Thanks man .... i knew that was a bad practise but didn't know there is a swap function in the standard library – py300 Oct 06 '22 at 07:02
  • Nice answer! @py300: As a rule of thumb, every useful function is in the standard library. – Bathsheba Oct 06 '22 at 08:53