Search code examples
cif-statementoperatorsinequality

Why is following expression TRUE?


I recently started learning C from Sams Teach Yourself C In 21 DAYS, and I can't understand why one expression evaluates to TRUE. It's one of the excersises at the end of the chapter.

x = 4
y = 6
z = 2
if(x != y - z)

I thought that "-" has higher precedence than "!=". What am I missing? I mean, it's getting late and I've been awake since 5am, so maybe my brain is giving up...


Solution

  • The expression in the if statement

    if(x != y - z)
    

    may be equivalently rewritten using parentheses like

    if(x != ( y - z ))
    

    because the additive operator - has a higher priority than the equality operator !=.

    As actually x is equal to the value of the expression y - z then the condition evaluates to the logical false.

    So it seems there is a typo in the book.