Search code examples
cfunctionreturnreturn-valueor-operator

C: OR operator in return line?


Came across some code that has an OR operator (||) in the return line. Could someone explain what that does ?


Here's something that looks like it:

int main()
{
    ...

    return (1 || 0);
}

But really it was a function (that returned 1 or 0) instead of the 1 and 0:

int main()
{
    ...

    return (foo(x++, y) || foo(x, y++));
}

Solution

  • a || b evaluates to 1 if a is non-zero irrespective of the value of b, evaluates to 1 if a is 0 and b is non-zero, else it's 0.

    So 1 || 0 is 1, as would be 2 || 0.

    Note that b is not evaluated if a is non-zero: so if b was a function, it would not be called in such a case. So in your example, foo(x, y++) is not called including the evaluation of y++ if foo(x++, y) is non-zero.

    Note that the type of a || b is an int irrespective of the type of the arguments. Cf. C++ where the type is a bool.