-2

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?

tocsika7
  • 3
  • 2

1 Answers1

3

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;.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • You example you gave would be correct with `||` instead of `&&`, or with `0` instead of `1` but in this case both operands needs to be evaluated. –  Mar 19 '19 at 09:50
  • 1
    @AsafRosemarin Yep typo, fixed. – Lundin Mar 19 '19 at 09:51