MaDiS
MaDiS

Reputation: 31

Why do these swap functions behave differently?

#include <stdio.h>

void swap1(int a, int b)
{
    int temp = a;

    a = b;
    b = temp;
}

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

    a = b;
    b = temp;
}

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

    *a = *b;
    *b = temp;
}

main()
{
    int a = 9, b = 4;

    printf("%d , %d\n", a, b);
    swap1(a, b);
    printf("%d , %d\n", a, b);
    swap2(&a, &b);
    printf("%d , %d\n", a, b);
    swap3(&a, &b);
    printf("%d , %d\n", a, b);

}

Upvotes: 2

Views: 226

Answers (5)

user2765861
user2765861

Reputation: 163

Just for fun, exchange values without the use of a temporary variable

x = x ^ y
y = x ^ y
x = x ^ y

Upvotes: 0

Shlublu
Shlublu

Reputation: 11027

swap1() and swap2() have an effect limited to the scope of the function itself: the variables they swap are parameters passed by copy, and any change applied to them does not impact the source variable of your main() that were copied during the function call.

swap3 works as it acts on the values pointed by the parameters, instead of acting on the parameters themselves. It is the only of the three that chage the value located at the memory adress in which your main()'s a and b variables are stored.

Upvotes: 0

Ruel
Ruel

Reputation: 15780

swap1 will not work because the function just copied the arguments, not affecting the variables in main.

swap2 will not work either.

Upvotes: 0

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

C has value semantics for function parameters. This means the a and b for all your three swap variants are local variables of the respective functions. They are copies of the values you pass as arguments. In other words:

  • swap1 exchanges values of two local integer variables - no visible effect outside the function
  • swap2 exchanges values of two local variables, which are pointers in this case, - same, no visible effect
  • swap3 finally gets it right and exchanges the values pointed to by local pointer variables.

Upvotes: 4

sje397
sje397

Reputation: 41822

You're swap2 function has no effect.

You are passing in two pointers. Inside the function, the (parameter) variables a and b are local to the function. The swap2 function just swaps the values of these local variables around - having no effect outside the function itself.

As Anon pointed out, swap1 has the same problem - you're just modifying local variables.

Upvotes: 2

Related Questions