Teuntje Teuntje - 1 month ago 5
C Question

Switching the values of variables in C

I have this function called

void rotateLeft(int *a, int *b, int *c, int *d)
. I want to give the variables a,b,c and d to this function. I want to call the function and then a needs to get the value of b, d the value of a, c the value of d and b the value of c. I have added my main code below where the function is being called and the code of the rotateLeft function. What do I put in the rotateLeft function to get it to work?

#include <stdio.h>
#include <stdlib.h>


void rotateLeft (int*, int*, int*, int*);

int main(int argc, char **argv){

int a,b,c,d,n;

while( (n = scanf("%d%d%d%d",&a,&b,&c,&d)) == 4)
{
rotateLeft(&a,&b,&c,&d);
printf("%d %d %d %d\n",a,b,c,d);
}

}


rotateLeft function

#include <stdio.h>
#include <stdlib.h>

void rotateLeft(int *a, int *b, int *c, int *d){




}

Answer

Okay, maybe I'm being stubborn expecting more code in the question.

Here's how I would solve it:

void rotateLeft(int *a, int *b, int *c, int *d){
  const int tmp = *a;
  *a = *b;
  *b = *c;
  *c = *d;
  *d = tmp; /* Because we've overwritten 'a', use a copy. */
}

Very straight-forward, I should hope.