Swapping variables

Level 2

The following C++ code swaps the two variables, x and y:

#include <iostream>

using namespace std;

void swap1(int left, int right)
{
    int temp;
    temp = left;
    left = right;
    right = temp;
}

void swap2(int *p_left, int *p_right)
{
    int temp = *p_left;
    *p_left = *p_right;
    *p_right = temp;
}

int main()
{
    int x = 1, y = 2;
    swap1(x, y);
    cout << x << " " << y << '\n';
    swap2(&x, &y);
    cout << x << " " << y << '\n';
}

Which of the functions correctly swaps the two values?

swap None swap2 swap1

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Jeyakumar Jp
Mar 11, 2014

In swap1 function it doesn't return values. But in swap2 function it change the the address of the values..

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...