Home > front end >  is it bad practice to call a function from within an if condition?
is it bad practice to call a function from within an if condition?

Time:10-02

hello< I am working on my first solo project in C and I have a bunch of sanity checks which call functions that return a bool. My question is it bad practice to call the the function from within the if condition or should I assign it's return value to a bool variable then use that variable in the condition. I'm teaching myself how to code and I am trying not pick up any bad habits. Below is a code example.

// This function checks user input for allowed operation 
// MAX_OPERATIONS is a macro that defines the max number of operations allowed
bool check_operation(char *n, char **ops)
{
    for (int i = 0; i < MAX_OPERATIONS; i  )
    {
        if (strcasecmp(n, ops[i]) == 0)
            return true;
    }
    return false;
}

// In main I call it like this
// operations_arr is an array of pointers that stores the operations 
// allowed in string format 
if (!check_operation(argv[1], operations_arr))
{
    error_message();
    return 1;
}

CodePudding user response:

There's nothing wrong with it. Though many C functions involve checking the result of parameters rather than the returned value and then you have no other option but to call the function on a line of its own.

Also, this is a common scenario:

result_t result = func();

if(result == ERR1)
  ...
else if(result == ERR2)
  ...

Here you can obviously not write

if(func() == ERR1)
  ...
else if(func() == ERR2)
  ...

Because then you end up calling the function twice, which is inefficient, but could also give different results.

As for using return from a function as a way to quickly stop executing and go directly to the error handler, it's actually likely the best way of doing so in C. Other alternatives are using messy boolean flags in the loop, or the "on error goto" pattern (which is usually OK but comes with the mandatory, tiresome "goto considered harmful" debate).

As for picking up bad habits: not using const correctness of read-only parameters is a bad habit.

CodePudding user response:

There's nothing wrong with it as such, but I'd argue it's better to assign it to a variable because by doing so you're writing explicit code.

Explicit code is easier to read and also easier to maintain. Right now you're returning a bool, but imagine in future you change your function to return an int in order to pass more information, then you'd possibly want to add more checks. Also, by assigning its value to an explicitly typed variable you're making it easier for compiler to do some basic type checking to guard you from errors that might arise from changing the return type of the function.

  •  Tags:  
  • c
  • Related