The swap() Function – Solution

This month’s Exercise is to code a function that swaps two variables. The challenge really isn’t to swap the variables, but to figure out how to code a function that does so.

Functions in C return only one value. The two tricks for getting around this limitation are to use a structure or pointers.

Using a structure wasn’t part of the original challenge code, though I suppose you could have added a structure to define two integer members and swap them within the swap() function. A better solution, however, is to use pointers, which is what I did:

2024_01-Exercise.c

#include <stdio.h>

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

int main()
{
    int x = 5;
    int y = 10;

    printf("Before swap: x=%d, y=%d\n",x,y);
    swap(&x, &y);
    printf("After swap: x=%d, y=%d\n",x,y);

    return 0;
}

The swap() function accepts two integer pointers as its arguments, a and b. These are passed from the main() function by address: The & operator obtains the address in the swap() function call.

In the swap() function, a third variable temp is created. It’s a pointer holding an address. It’s used to swap the two values, the memory locations, stored in passed variables a and b.

Nothing is returned from the function as the variables’ addresses are swapped. The values aren’t really affected.

Of course, you could have coded the swap() function to swap the values and not the addresses. Here’s how this variation looks:

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

Variable temp is an integer. It snatches the value stored at the address in a, then swap works with dereferenced pointers. The output is the same.

Either solution is possible. You may have come up with another solution as well. If so, and if the output looks like this:

Before swap: x=5, y=10
After swap: x=10, y=5

You’ve passed the challenge.

3 thoughts on “The swap() Function – Solution

  1. Is there a reason you put functions first and main at the bottom? I prefer to use function prototypes, then main and finally the functions themselves. The prototypes provide a concise reference for when I forget the arguments and return type of the function I wrote 5 minutes ago.

  2. I just started doing that a while back. I agree that it’s easier to see the prototypes up top to know what’s going on. I think I did it as I started putting fewer statements in main() and opted to offload things into functions.

  3. I always define functions above main() as well. I think for me it’s a hangover from learning to code in Pascal, which requires functions and procedures to be defined explicitly before the main code block.

Leave a Reply