简体   繁体   中英

Make multiple assignments more optimal

I have one simple function that memorize a couple of previous values. Can someone help me to make this function more compact. More exactly I want to do all the assignments in a more optimal way. If it is someone to help me I will be very thankfully.

 xy snake_body(int x,int y)
    {
     xy body;

       body.x = x_loop_16;
       body.y = y_loop_16;

       x_loop_16 = x_loop_15;
       y_loop_16 = y_loop_15;

       x_loop_15 = x_loop_14;
       y_loop_15 = y_loop_14;

       x_loop_14 = x_loop_13;
       y_loop_14 = y_loop_13;

       x_loop_13 = x_loop_12;
       y_loop_13 = y_loop_12;

       x_loop_12 = x_loop_11;
       y_loop_12 = y_loop_11;

       x_loop_11 = x_loop_10;
       y_loop_11 = y_loop_10;

       x_loop_10 = x_loop_9;
       y_loop_10 = y_loop_9;

       x_loop_9 = x_loop_8;
       y_loop_9 = y_loop_8;

       x_loop_8 = x_loop_7;
       y_loop_8 = y_loop_7;

       x_loop_7 = x_loop_6;
       y_loop_7 = y_loop_6;

       x_loop_6 = x_loop_5;
       y_loop_6 = y_loop_5;

       x_loop_5 = x_loop_4;
       y_loop_5 = y_loop_4;

       x_loop_4 = x_loop_3;
       y_loop_4 = y_loop_3;

       x_loop_3 = x_loop_2;
       y_loop_3 = y_loop_2;

       x_loop_2 = x_loop_1;
       y_loop_2 = y_loop_1;

       x_loop_1 = x;
       y_loop_1 = y;

        return body;

    }

"xy" is a structure variable. I use it to store the data that comes from "x" and "y", and also to have multiple returns from "snake_body" function. I hope I was enough specific and if there are any questions, I will respond them as quick as I can. Thank you.

Instead of using 2x16 variables just use two arrays and loop over it.

You roughly want this:

int x_loop[16];
int y_loop[16];

xy snake_body(int x, int y)
{
  xy body;

  body.x = x_loop]15];
  body.y = y_loop[15];

  for (int i = 15; i > 0; i--)
  {
    x_loop[i] = x_loop[i - 1];
    y_loop[i] = y_loop[i - 1];
  }

  x_loop[0] = x;
  y_loop[0] = y;

  return body;
}

But there are more elegant ways to solve this problem, especially using a circular buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM