Search code examples
cperformanceerror-handlingconditional-statementsreadability

Which code style is better in terms of readability and performance?


I am wondering which code style is better for

  1. human readability
  2. program performance

Let's imagine we have 2 functions:

// first one
void foo(void) {
    if (error)
        exit(1);
    ....
}

// second one
void bar(void) {
    if (!error) {
        ....
    }
    else
        exit(1);
}

Both of them work in the same way in terms of execution, but which code style is preferable?


Solution

  • If I had to choose out of these two only, I'd choose the first one.

    Reason:

    1. It's simple. (does not use any operator like !)
    2. It does not need comments to explain what happens inside. (self-readable code)
    3. It avoids extra pair of { } which makes the code more readable
    4. Both performs nearly the same, I highly doubt there will be a difference in performance.

    Hence, first one is preferable.