-2

I have no idea how the following code returns 10. I expected that the x>2||(y%2) part meant that x should either be bigger than two or bigger than y%2.

int x, y = 1;
for (x = 10; x > 2 || (y % 2); x--) {
y = y + 1;
}
printf ("%d\n", y);

when I change it to the following, I get my expected output (11):

int x, y = 1;
for (x = 10; x > 2 || x > (y % 2); x--) {
y = y + 1;
}
printf ("%d\n", y);

how is the second code different from the first one?

  • 1
    nope, `x > 2 || (y % 2)` means "`x > 2`" or "`y` is odd". how could the compiler could understand what you want ? – Jean-François Fabre Mar 10 '18 at 22:28
  • see here: https://stackoverflow.com/questions/15181579/c-most-efficient-way-to-compare-a-variable-to-multiple-values – Jean-François Fabre Mar 10 '18 at 22:31
  • You will want to learn about operator precedence – imabug Mar 10 '18 at 22:32
  • x > 2 || (y % 2) does not evaluate as x > 2 or x > (y % 2). Instead, the integer y % 2 is is converted to a boolean as 1 -> true and 0 -> false – acai Mar 10 '18 at 22:33
  • Thanks a lot Jean-François and acai, that clears things up. – Martijn Huiskes Mar 10 '18 at 22:35
  • @imabug this isn't operator precedence. Put the parentheses anywhere you want, you cannot achieve what OP wants. it's just that `||` isn't distributed to each one of the conditions. – Jean-François Fabre Mar 10 '18 at 22:40
  • if someone finds a good duplicate of that one, I'll close it. I haven't found one specifically for c or even c++, even if this question comes back a lot in python for instance. – Jean-François Fabre Mar 10 '18 at 22:43
  • @Jean-FrançoisFabre This is true, but OP being more familiar with operator precedence rules wouldn't have needed to ask the question – imabug Mar 10 '18 at 22:51
  • it's _not_ operator precedence. Operator precedence is when you have `a + b * c` and the result is incorrect, now adding parentheses like `(a + b) * c` then the result is correct. – Jean-François Fabre Mar 10 '18 at 22:53
  • Does this answer your question? [C++ Most efficient way to compare a variable to multiple values?](https://stackoverflow.com/questions/15181579/c-most-efficient-way-to-compare-a-variable-to-multiple-values) – cigien Jul 23 '21 at 23:16

1 Answers1

0
x > 2 || (y % 2)

first tests x > 2, and if this is false, then tests (y % 2) (y is odd).

The || operator doesn't and cannot apply to the > operator, the || operation is performed exactly once, not twice. It's the C variant of the classic Python mistake showcased here: How do I test multiple variables against a value?, where trying to use natural language in a computer language fails.

(BTW it's not operator precedence, operator precedence would be between that expression and x > (2 || (y % 2)), still not what you're looking for)

Also related: C++ Most efficient way to compare a variable to multiple values?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219