arrayscloopsif-statementfunction-definition

C: how to convert this code for an use with array?


Consider I'm still a newbie with C, so I made a lot of confusion. This code works fine

int error(int a, int b, int c)
{ 
  
  if (( a < 0 ) || (a > 255)) {
  printf("Number is over 255 or under 0, exit \n");
  exit(1); }

  if ((a < 0)|| (a > 255)) {
  printf("Number is over 255 or under 0, exit \n");
  exit(1);
  }
  else if ((b < 0)|| (b > 255)) {
  printf("Number is over 255 or under 0, exit \n");
  exit(1);
  } 
  else if ((c < 0)|| (c > 255)) {
  printf("Number is over 255 or under 0, exit \n");
  exit(1);
  } 
  else {
  true;
 }
}

But is too long and I don't like it, I want to create an array which take the values of a b and c, and compare it with 255 or 0 (separately: for example a=256 failed, b=23 ok, c=33 ok), and if is over 255 or under 0, exit. I have tried this code but I have failed

int array[] = {a, b, c};
  
        if( array[a] >= MAX_SIZE){
         printf("Number is over 255 or under 0, exit \n");
         exit(1);
     } 

Solution

  • For starters it is not a godd design when the program exits from the function.

    Using an array your function can look the following way

    bool error(int a, int b, int c)
    { 
        int data[] = { a, b, c };
        size_t n = sizeof( data ) / sizeof( *data );
    
        size_t i = 0;
    
        while ( i < n && !( data[i] < 0 || data[i] > 255 ) ) i++;
    
        if ( i != n )
        {   
            printf("Number is over 255 or under 0, exit \n");
        }
    
        return i == n;
    }
    

    Though as the function is named error then it should return true when the numbers do not satisfy the condition that is it is better to rewrite the return statement like

    return i != n;
    

    Also pay attention to that the function should not output any message. It is the caller of the function based on the return value will decide whether to output a message. So I would define the function the following way

    bool error(int a, int b, int c)
    { 
        int data[] = { a, b, c };
        size_t n = sizeof( data ) / sizeof( *data );
    
        size_t i = 0;
    
        while ( i < n && !( data[i] < 0 || data[i] > 255 ) ) i++;
    
        return i != n;
    }
    

    and in the caller you can write

    if ( error( a, b, c ) )
    {
        printf("Number is over 255 or under 0, exit \n");
    }
    

    If you want to use an array of values then the function can look the following way

    bool error( const int data[], size_t n, int low, int high )
    { 
        size_t i = 0;
    
        while ( i < n && !( data[i] < low || data[i] > high ) ) i++;
    
        return i != n;
    }
    

    The values of low and high can be for example 1 and 255.