Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a semi-colon right after this for loop?

Tags:

java

for-loop

I came across this code

for(; tail < len;tail++){
        str[tail] = 0;

Why is there a ";" right after the "for("?

When I took it out, it came up with a couple errors.

like image 261
user1292548 Avatar asked Dec 18 '25 10:12

user1292548


1 Answers

It means that there is no initialization (it has already been done on previous lines).

In general a for loop has the following syntax:

for (initialization; termination; increment) {
    statement(s)
}

All three expressions (initialization, termination and increment) are optional, but the semi-colons must be present. The code you have is equivalent to the following while loop:

while (tail < len) {
    str[tail] = 0;
    tail++;
}

It is also common to see for loops where all three expressions are missing:

for (;;) {
    // something
}

This is an infinite loop and equivalent to this:

while (true) {
    // something
}
like image 89
Mark Byers Avatar answered Dec 21 '25 01:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!