-7

I'm new to the C programming language and trying to understand the operator precedence in the following code

int main() 
{
    int i = 10;
    if (i == 20 || 30)
        printf("true");
    else
        printf("false");
    return 0;
}

the output is 'True' in the above case.

Also, if I replace condition "||" with "&&" the output is 'False'. Again is it because of the precedence of the operator "||" or "&&" over "=="?

Could anyone please explain whether the above assumption is correct or not? and any further details if I'm missing any?

4 Answers4

3

As with any translation between languages, you don't necessarily preserve meaning by making word-for-word substitutions.

The English phrase "x is y or z" tends to translate in technical languages as something more analogous to "x is y or x is z" or "x is an element of the collection containing y and z".

What you want is i == 20 || i == 30.

The expression you wrote, i == 20 || 30 translates to "i is 20, or true" which is the same thing as "true". The reason is that 30, in this context, effectively gets converted to a boolean, and since 30 is nonzero, it converts to "true".

A third variation you might have written is i == (20 || 30), which would be equivalent to i == 1 (because 20 and 30 convert to true, then true converts back to 1).

3

Because of operator precedence the condition

int i = 10;
if (i == 20 || 30)

is equivalent to

if ((i == 20) || 30)

so the first test if false, the second, being non-0, evaluates to true. Since one of the two evaluations is true, the whole test is true.

What happens when you replace || with &&?

if ((i == 20) && 30)

here since one of the two evaluations is false, the whole test is false.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
1

Because every value other than 0 is true. In the condition it say if i equals to 20 that is false or by 30 that is true and makes the whole statement true. If you change the or with an and then the statement will be false.

Alikbar
  • 685
  • 6
  • 20
0

30 is logically true. Any non-zero value is true. The OR expression evaluates to true because the 30 is logically true.

Change the OR to AND causes the expression to become logically false.

nicomp
  • 4,344
  • 4
  • 27
  • 60