c++call-by-value

why in this code swapping happens when the "swap" function is written after int main() but not before it?


So my doubt is, I was trying out call by value, While running the given code, Swapping happens when I write the function definition after int main() But if I cut and paste the function definition above int main(), the swap does not take place. Why is that?


#include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<fstream>
using namespace std;
#define ADDU 1
#define SUBU 3
#define AND 4
#define OR  5
#define NOR 7
#define MemSize 65536
void swap(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
}

int main(){
    // int a = 20;
    // int *p = &a;
    // cout<<"P: "<<p<<endl<<"*P gives: "<<*p<<endl<<"&p gives: "<<&p<<endl<<"&a : "<<&a;;

    int x,y;
    x = 10;
    y = 20;
    cout<<"Before Swapping: "<<"x: "<<x<<endl<<"y: "<<y<<endl;
    swap(x,y);
    cout<<"After Swapping: "<<"x: "<<x<<endl<<"y: "<<y<<endl;
}

Solution

  • Your swap function doesn't really swap anything, because it takes its arguments by value rather than by reference. All you're doing is manipulating variables that are local to that function.

    When you don't introduce it until after main, it's not in scope when you call it, so std::swap is used instead. std::swap works correctly.

    Although you didn't specifically say std::swap, you wrote using namespace std; which removes that requirement (good reason not to do it!!). And, although you did not #include <algorithm>, you cannot guarantee which standard headers may end up including other ones by virtue of how the implementation is constructed.