Home > Software design >  Remove goto in C
Remove goto in C

Time:04-20

I want to remove goto statements in my C code. The following shows my C code.

void placeFruit(void)
{ 
 resetfruitX:fruitX=rand() ;
 if(fruitX==0||fruitX==width)
 goto resetfruitX;

 resetfruitY:fruitY=rand() ;
 if(fruitY==0||fruitY==height)
 goto resetfruitY;
}

Can anyone help me?

CodePudding user response:

void placeFruit(void){    
  do fruitX=rand() ; while(fruitX==0||fruitX==width);
  do fruitY=rand() ; while(fruitY==0||fruitY==width);
}

CodePudding user response:

Use loops and perhaps improve readability a bit with an internal helper function:

static inline int place (int max)
{
  int fruit=0;

  while(fruit==0 || fruit==max)
    fruit = rand() % 20;

  return fruit;
}

void placeFruit(void)
{ 
  fruitX = place(width);
  fruitY = place(height);
}

do-while is a micro-optimization over while but works too - it doesn't matter much which one you pick. The performance bottleneck here is the rand() call. In theory this loop could go on for ever, so maybe consider a better strategy like having two containers/matrices, one with "used" coordinates and one with "free" coordinates.

  •  Tags:  
  • c
  • Related