question about conditional operator (?:)

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 26 06:19:54 PDT 2016


On 07/26/2016 03:09 PM, Richard wrote:
>         if(n%p==0)
>             n/=p;
>         else
>             p+=1;
[...]
> However, if I replace the content of the for loop with the ?: operator,
> the program is not
> correct anymore (largestPrimeFactor(4) now returns 3):
[...]
>         n%p==0 ? n/=p : p+=1 ;
[...]
> What am I doing wrong here?

Operator precedence is different from what you think. `a ? b : c = d` 
means `(a ? b : c) = d`. But you want `a ? b : (c = d)`. So you need 
parentheses around `p+=1`.

Or just go with `if` and `else`. It's clearer anyway.


More information about the Digitalmars-d-learn mailing list