Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use ?: operators in the 3rd argument of for loops in Java?

Tags:

java

for-loop

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); } 
like image 278
Izumi Kawashima Avatar asked Mar 22 '14 13:03

Izumi Kawashima


People also ask

How do you control a for loop in Java?

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.

Can you change i in a for loop Java?

Yes you can change index inside a for loop but it is too confusing. Better use a while loop in such case.


1 Answers

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 StatementExpressions, 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.

like image 174
eis Avatar answered Nov 05 '22 00:11

eis