Search code examples
c++staticpass-by-referencepass-by-value

Why cant i swap 2 numbers using static variables if static variables have only one copy stored for the whole part of the program?


If static variables has only one copy for the program. So why is it not possible to swap 2 numbers using another function?

Code:

#include <iostream>

void swap(int, int);

int main()
{
    static int a = 1;
    static int b = 2;
    swap(a, b);
    std::cout << "a = " << a << std::endl << "b = " << b << std::endl;
    std::cin.get();
}

void swap(int a,int b)
{
    int temp = a;
    a = b;
    b = temp;
    std::cout << "a = " << a << std::endl << "b = " << b << std::endl;
}

Solution

  • As the 'swap' function is taking parameters as pass by value, copies of the variables are passed to the swap function which will only swap its local variables 'a' and 'b' (passed as parameter) not the static ones passed from main.

    Swap should be taking parameters as references like below.

    #include <iostream>
    
    void swap(int&, int&);
    
    int main()
    {
        static int a = 1;
        static int b = 2;
        swap(a, b);
        std::cout << "a = " << a << std::endl << "b = " << b << std::endl;
        std::cin.get();
    }
    
    void swap(int &a,int &b)
    {
        int temp = a;
        a = b;
        b = temp;
        std::cout << "a = " << a << std::endl << "b = " << b << std::endl;
    }
    

    Please note that static variable defined in a function pertains its value in the subsequent calls of the function in which it is declared.