0

Let's say I've two ways of writing a piece of code:

Way 1:

int TailX[100];
int TailY[100];
int prevX = TailX[0];
int prevY = TailY[0];
TailX[0] = x;
TailY[0] = y;

int prev2X, prev2Y;
for(int i=1; i< nTail; i++){
 prev2X = TailX[i];
 prev2Y = TailY[i];
 TailX[i] = prevX;
 TailY[i] = prevY;
 prevX = prev2X;
 prevY =prev2Y;
 }

Way 2:

int TailX[100];
int TailY[100];
TailX[0] = x;
TailY[0] = y;
int prevX = TailX[0];
int prevY = TailY[0];


int prev2X, prev2Y;
for(int i=1; i< nTail; i++){
   prev2X = TailX[i];
   prev2Y = TailY[i];
   TailX[i] = prevX;
   TailY[i] = prevY;
   prevX = prev2X;
   prevY =prev2Y;
 }

I am trying to design a snake game and this chunk of the code is to store the coordinates of the previous block so as to follow it. The above code (Way 1) is working properly whereas the latter code (Way 2) is resulting in the block after the head-block to be attached to its right side while the snake is moving vertically up or down.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 2
    `int TailX[100]; int prevX = TailX[0];` you're getting UB because `TailX` hasn't been initialized yet. [(Why) is using an uninitialized variable undefined behavior?](https://stackoverflow.com/q/11962457/995714) – phuclv Apr 08 '22 at 17:04
  • 1
    Assuming the arrays are initialized properly, then `TailX[0] = x;` followed by `int prevX = TailX[0];` would just be the same as `int prevX = x;` – Some programmer dude Apr 08 '22 at 17:06
  • If you set (way2) prevX value after set TailX[0]=x, your prevX value is equal to x. If you set (way1) prevX value before set TailX[0]=x, your prevX is different to x. – Victor Apr 08 '22 at 17:35
  • @phuclv Thanks for the suggestion... however in my case, the code is working properly when it isn't initialized initially..and is creating an undesirable behavior when initialized earlier and then allotted to a variable – Aditi Bhattacharya Apr 09 '22 at 05:54
  • @Victor Okay.. I get it now.. Thanks – Aditi Bhattacharya Apr 09 '22 at 06:02
  • @AditiBhattacharya Undefined behavior means anything can happen, including the program produces a valid output, changes the behavior when changing compiler/compiler version/OS... or [make flying nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). See https://en.wikipedia.org/wiki/Undefined_behavior, [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/q/2397984/995714). Enable warnings and the compiler will show you the issue immediately. See [Why should I always enable compiler warnings?](https://stackoverflow.com/q/57842756/995714) – phuclv Apr 09 '22 at 06:14

0 Answers0