Simple linearity problem in C

0

I have a question about this procedure. Could this exchange of variables be simplified without using an auxiliary variable?

Practicing with pointers I came up with this dilemma and I do not know another solution to this problem. The idea is that each instruction is executed in a linear way so there is no case that it can replace "aux" because either first change the value from n1 to n2 or from n2 to n1. My idea is to learn new techniques.

int main()
{
    int n1=2;
    int n2=5;
    int aux=0;
    int *p1 = &n1;
    int *p2 = &n2;

    aux = n1;
    *p1 = n2;
    *p2 = aux;

    printf("%d %d",n1,n2);

    return 0;
}
    
asked by GuilleX 14.07.2018 в 18:33
source

1 answer

2

If it's 2 integer variables , one solution would be to use the XOR operator:

n1 = n1 ^ n2;
n2 = n2 ^ n1;
n1 = n1 ^ n2;

Bit operations have many uses, this is one of them.

It is very good to learn new techniques and ways of solving problems, never lose your curiosity that that is what makes a good programmer, greetings!

    
answered by 15.07.2018 / 01:44
source