1
#include<stdio.h>
#include<cs50.h>
void swap(int x,int y);
int main(void)
{
int x=get_int(),y=get_int();
printf("1=%i and 2=%i",x,y);
swap(x,y);
printf("1=%i and 2=%i",x,y);
}
void swap(int x,int y)
{
int z=x;
x=y;
y=z;

}

Implemented the following code to swap two integers. It does not work. Can someone point out the mistake? Is it in the return type?

1
0

Although the link bellow the question is adequate, I add the answer so that the question is no longer listed under the unanswered questions.

The return type of dwap() should be void, since in doesn't return anything, the swapping is happening to the two variables passed by reference (by their pointers actually) and the result is stored in the same variables. Here is a working example of the swap function:

#include <stdio.h>

// prototype
void swap(int *a, int *b);

int main(int argc, char const *argv[])
{
    int a = 42;
    int b = 50;

    printf("a = %d\n", a);
    printf("b = %d\n", b);

    printf("Swapping...\n");

    // we pass the pointers to a and b
    swap(&a, &b);

    printf("Swapped!\n");

    printf("a = %d\n", a);
    printf("b = %d\n", b);

    return 0;
}

/**
 * Swaps the values pointed by a and b
 */
void swap(int *a, int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

with output:

a = 42
b = 50
Swapping...
Swapped!
a = 50
b = 42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .