Why is the following code giving me an error?
int n = 30000; // Some number for (int i = 0; 0 <= n ? (i < n) : (i > n); 0 <= n ? (i++) : (i--)) { // ## Error "not a statement" ## f(i,n); }
It tests the condition before executing the loop body. Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. Like a while statement, except that it tests the condition at the end of the loop body.
Yes you can change index inside a for loop but it is too confusing. Better use a while loop in such case.
It's because the for
loop has been defined that way in the Java Language Specification.
14.14.1 The basic for statement
BasicForStatement: for ( ForInit ; Expression ; ForUpdate ) Statement ForStatementNoShortIf: for ( ForInit ; Expression ; ForUpdate ) StatementNoShortIf ForInit: StatementExpressionList LocalVariableDeclaration ForUpdate: StatementExpressionList StatementExpressionList: StatementExpression StatementExpressionList , StatementExpression
So it needs to be a StatementExpression
or multiple StatementExpression
s, and StatementExpression
is defined as:
14.8 Expression statements
StatementExpression: Assignment PreIncrementExpression PreDecrementExpression PostIncrementExpression PostDecrementExpression MethodInvocation ClassInstanceCreationExpression
0 <= n ? (i++) : (i--)
is none of those, so it is not accepted. i += ((0 <= n) ? 1 : -1)
is an assignment, so it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With