Search code examples
creturnlogical-operators

Logoical operators in return


I have a function in a program that should return an int, but the return looks like this:

return wordlength > 6.0 &&  wordlength< 9.0
       && strcasestr (string, "substring1") && strcasestr (string, "substring2")
       && strcasestr (string, "substring2") && strcasestr (string, "substring4")

The wordlength is a double that contains the average length of the words in the string.

My question is what does the return statement actually return?


Solution

  • The operator precedence rules say that relational operators like < take precedence over &&. Therefore the sub-expression wordlength > 6.0 && wordlength< 9.0 is equivalent to (wordlength > 6.0) && (wordlength< 9.0).

    Once that's sorted out, note that && has left-to-right associativity. Meaning that in case there are several of the same operator with the same precedence in the same expression, like for example a && b && c, then it is equivalent to (a && b) && c.

    The logical operators like && has a "short-circuit" order of evaluation. Meaning that in 0 && b, only the operand 0 is evaluated/executed. See Is short-circuiting logical operators mandated? And evaluation order?

    And finally, logically expressions in C do not yield a boolean type (like in C++) but an int of value 1 or 0. Even though the type is int, this can be regarded as if it is of type bool though, and you can safely write code such as bool b = x && y;.