Utilisation de pointeurs
Le code
#include <stdio.h>
void change(int *,int*);
int main ()
{
int a=2,b=5;
printf("Avant : a=%d,b=%d\n",a,b);
change(&a,&b);
printf("Apres : a=%d,b=%d\n",a,b);
return 0;
}
void change(int *a,int *b){
*a += *b;
*b = *a-*b;
*a = *a-*b;
}
Le résultat
lami20j@debian:~/trash$ gcc permuter_var.c
lami20j@debian:~/trash$ ./a.out
Avant : a=2,b=5
Apres : a=5,b=2
Utilisation d'une macro
Code :
#include <stdio.h>
#define PERMUTER(x,y) x ^= y, y ^= x, x ^= y
int main ()
{
int a=2,b=5;
printf("Avant : a=%d,b=%d\n",a,b);
PERMUTER(a,b);
printf("Apres : a=%d,b=%d\n",a,b);
return 0;
}
Le résultat
vlmath@debian:~$ gcc permuter_var.c
vlmath@debian:~$ ./a.out
Avant : a=2,b=5
Apres : a=5,b=2
Remarque
Le nom de la macro, ou de ses variables, peut naturellement être changé.