As an example the following one:
double b = 1.0;
int v[] = {1,1,1,0,1,0,1};
double a[] = {0.001953125, 0.00390625, 0.0078125, 0.015625, 0.03125, 0.0625, -0.125};
System.out.println(b);
for(int i = 0; i <7; i++)
{
b = b + v[i] == 0 ? a[i] : -a[i];
System.out.println(b);
}
gives:
1.0
-0.001953125
-0.00390625
-0.0078125
-0.015625
-0.03125
-0.0625
0.125
and this one:
double b = 1.0;
int v[] = {1,1,1,0,1,0,1};
double a[] = {0.001953125, 0.00390625, 0.0078125, 0.015625, 0.03125, 0.0625, -0.125};
System.out.println(b);
for(int i = 0; i <7; i++)
{
b = b + (v[i] == 0 ? a[i] : -a[i]);
System.out.println(b);
}
gives:
1.0
0.998046875
0.994140625
0.986328125
1.001953125
0.970703125
1.033203125
1.158203125
Does this means that the value of b is changed to 0 first in the first one (without the brackets) or set directly to the value of a[i] ?!
Using ? for if/else in addition means that I have to use brackets around the condition/if/else part ?! Thanks.
This because of precedence of operators,
b + v[i] == 0 ? a[i] : -a[i]is parsed asSince
+has higher priority than==, the expression has a different semantics from the one you think.You could avoid the problem by using parenthesis to enforce evaulation order or by using a
+=operator which makes the problem disappear in this specific case.