-1

i cant understand the second line of the below code:

for (int i = n - 1; i >= 0; i--)
{
   ans += (a[i] - ans * r > 0);
   printf("%d\n", ans);
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
ifahim1000
  • 13
  • 1
  • 1
    With https://en.cppreference.com/w/cpp/language/operator_precedence you will see that `(a[i] - ans * r > 0)` is equivalent to `(((a[i]) - (ans * r)) > 0)`. The value of `(a[i]) - (ans * r)` is compared with `0`. The result is converted to the type of `ans`. If it's a numeric type: true => 1, false => 0 – Thomas Sablik Oct 09 '19 at 19:14

1 Answers1

3

When in doubt, simplify.

Due to operator precedence, the line

ans += (a[i] - ans * r > 0);

is equivalent to:

ans += ((a[i] - ans * r) > 0);

To make it more readable, use:

bool temp1 = ((a[i] - ans * r) > 0);
ans += temp1;

When used in a term such as ans += temp1, a bool gets converted/promoted to 1 if the value is true and to 0 if the value is false.

A further simplification would be:

bool temp1 = ((a[i] - ans * r) > 0);
int temp2 = (temp1? 1 : 0);
ans += temp2;

In the end, ans gets incremented by 1 if (a[i] - ans * r) > 0. Otherwise, its value remains unchanged.

R Sahu
  • 204,454
  • 14
  • 159
  • 270