Search code examples
ccoding-style

Is it possible to insert an if condition inside a return statement in C?


My purpose is trying to write a function as concise and short as possible.

int func(void)
{
    int a;
    return (
        a = 42,
        a++,
        if (a > 42) a *= -1,
        a);
}

I was expecting to return a -43. Instead I've got a compilation error.


Solution

  • My purpose is trying to write a function as concise and short as possible.

    int a;
    
    return (
       a = 42,
       a++,
       if (a > 42) a *= -1,
       a);
    

    Can simply be rewritten as:

    return -43;
    

    Or if that's too short for your liking, then you're looking for the conditional operator (colloquially referred to as the ternary operator), which has the form:

    /* if a is logically true (does not evaluate to zero) 
    *  then evaluate expression b, otherwise 
    *  evaluate expression c
    */
    a ? b : c;
    

    So the return statement can be rewritten as:

    a = 42;
    return ++a > 42 ? -a : a;
    

    As of your objective, then there's no merit to it. You should not write clever code. It harms readability and maintainability. (Although in this case, it doesn't)

    Remember:

    1. Simplicity is the ultimate sophistication.Leonardo da Vinci
    2. Any fool can write code that a computer can understand. Good programmers write code that humans can understand.Martin Fowler
    3. Everything should be made as simple as possible — but no simpler.Albert Einstein (attributed).¹

    [1] — credit: @SteveSummit