Search code examples
cgoto

C-loops and goto


How can i remove the goto from the following code?

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

bool is_prime(unsigned num)
{

   if(num==0 || num==1)
     return false;
   if(num==2)
     return true;
   for(unsigned i=2;i<=num-1;i++)
    if(num%i==0)
        goto step;

             return true;
      step:  return false;
}


int main(void)
{
  unsigned n;
  printf("enter the number: ");
  scanf("%u",&n);
  printf("%u\n",is_prime(n));
  return 0;
}

Solution

  • Replace it with return false;. return exits a function. The code even relies on that behaviour already.

    bool is_prime(unsigned num)
    {
        if(num == 0 || num == 1)
            return false;
        for(int i = 2; i < num - 1; i++)
            if(num % i == 0)
                return false;
    
        return true;
    }