digitalmars.D.learn - Assignment in ternary condition operator
- JN (8/8) Aug 07 2018 int a, b;
- Steven Schveighoffer (16/28) Aug 07 2018 But operator precedence says that this is really:
- JN (5/23) Aug 07 2018 Ahhhh. I didn't think of that. Hmm, I guess a warning here would
int a, b; if (a = 3) { } <- not allowed: Error: assignment cannot be used as a condition, perhaps == was meant? b = a = 3 ? 4 : 5 <- allowed I believe the second case should be disallowed also. It seems illogical, that the first one isn't allowed, but the second one is, when the second one is also 'assignment used as condition'. Is there a valid usecase for such assignment?
Aug 07 2018
On 8/7/18 3:18 PM, JN wrote:int a, b; if (a = 3) { } <- not allowed: Error: assignment cannot be used as a condition, perhaps == was meant? b = a = 3 ? 4 : 5 <- allowed I believe the second case should be disallowed also. It seems illogical, that the first one isn't allowed, but the second one is, when the second one is also 'assignment used as condition'. Is there a valid usecase for such assignment?But operator precedence says that this is really: b = (a = (3 ? 4 : 5)) It's a different thing than the if statement. In the if statement, it's the *assignment* that is now the condition. Here, it is not an assignment that is the condition, but `3`. There is no common error that requires preventing assignment from the result of an assignment. I realize that what you seeing is a typo from: b = a == 3 ? 4 : 5 but the problem is that you are relying on precedence incorrectly here. If you type: b = (a = 3) ? 4 : 5 Then you get the error. D can't solve all the problems. Best thing to do is to use parentheses to clarify what you want for your condition rather than rely on default order of operations. -Steve
Aug 07 2018
On Tuesday, 7 August 2018 at 19:58:40 UTC, Steven Schveighoffer wrote:On 8/7/18 3:18 PM, JN wrote:Ahhhh. I didn't think of that. Hmm, I guess a warning here would be nice then, or perhaps DScanner could mark such cases as suspicious :)[...]But operator precedence says that this is really: b = (a = (3 ? 4 : 5)) It's a different thing than the if statement. In the if statement, it's the *assignment* that is now the condition. Here, it is not an assignment that is the condition, but `3`. There is no common error that requires preventing assignment from the result of an assignment. I realize that what you seeing is a typo from: b = a == 3 ? 4 : 5 but the problem is that you are relying on precedence incorrectly here. If you type: b = (a = 3) ? 4 : 5 Then you get the error. D can't solve all the problems. Best thing to do is to use parentheses to clarify what you want for your condition rather than rely on default order of operations. -Steve
Aug 07 2018