james_dean
james_dean

Reputation: 1517

Why does the increment/decrement in a for loop not end with a statement?

Everywhere else I write a statement in Java I need to end it with a semi-colon. However, that doesn't apply to the i++ of a for loop.

How comes?

Upvotes: 2

Views: 694

Answers (5)

Patrick87
Patrick87

Reputation: 28302

Because it's special syntax with clear and agreed-upon semantic meaning interpretable by the compiler, because the designers of C/C++/Java/etc. arbitarily decided it should be so.

EDIT:

Some commenters have pointed out that the decision isn't really arbitary, since designers did it to maintain consistency with expression vs. statement syntax. I'm glad they pointed that out, because I didn't know that was the case. In my defense, they very clearly could have made the syntax require a semicolon in that position; the decision not to, while not entirely arbitrarily, represented a choice which could have been different. Ahem.

Upvotes: 2

Charlie Martin
Charlie Martin

Reputation: 112366

If you think about it, really two of the three terms in a for loop aren't really statements. Take the canonical for loop

for(int ix = 0; ix < MAX; ix++){ /* do something */ }

that's really shorthand for

int ix = 0;
while(ix < MAX){ /* do something */ ; ix++; }

Notice that there's no semicolon for ix < MAX either. In the for loop, the semicolons are simply there to separate the terms somehow -- only by co-incidence (and a lack of extra symbols) is it the same as a statement terminator.

Upvotes: 1

vcsjones
vcsjones

Reputation: 141638

I would spend some time learning the differences between an expression and a statement; as described here.

The parts of a for loop are expressions, not statements. Expressions are not terminated by semicolons. i++ is an expression. Likewise, you don't put a semicolon after the i++ here:

System.out.println(i++;);
//                    ^ wrong

That wouldn't make any sense. The same logic applies to if, and while loops.

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236014

Both in C and C++ it's like that, and Java copied much of the syntax of those languages, for making things easier for programmers coming from them.

Also, it really isn't necessary to end the statement with a ";", since the right parenthesis ")" demarcates where the statement ends.

Upvotes: 1

Sean Owen
Sean Owen

Reputation: 66886

Because the ')' rather well terminates the update statement so it would be redundant?

Upvotes: 2

Related Questions