What does just “;” inside an “if” block mean? [duplicate]

It’s an empty statement. A single semicolon by itself performs no operation.

In this context, it means that if the if condition is true, do nothing.

Without an else section, there is not much use to this code. If there is, then it’s a matter of style whether the condition should be inverted and should contain just a non-empty if portion.

In this case it’s a simple conditional, so style-wise it’s probably better to invert it, however if the condition is more complicated it may be clearer to write this way. For example, this:

if ((a==1) && (b==2) && (c==3) && (d==4)) {
    ;
} else {
    // do something useful
}

Might be clearer than this:

if (!((a==1) && (b==2) && (c==3) && (d==4))) {
    // do something useful
}

Or this:

if ((a!=1) || (b!=2) || (c!=3) || (d!=4)) {
    // do something useful
}

A better example from the comments (thanks Ben):

if (not_found) {
    ;
} else {
    // do something
}

Versus:

if (!not_found) {
    // do something
}

Which method to use depends largely on exactly what is being compared, how many terms there are, how nested the terms are, and even the names of the variables / functions involved.

Another example of when you might use this is when you have a set of if..else statements to check a range of values and you want to document in the code that nothing should happen for a particular range:

if (a < 0) {
    process_negative(a);
} else if (a >=0 && a < 10) {
    process_under_10(a);
} else if (a >=10 && a < 20) {
    ;   // do nothing
} else if (a >=20 && a < 30) {
    process_20s(a);
} else if (a >= 30) {
    process_30s_and_up(a);
}

If the empty if was left out, a reader might wonder if something should have happened there and the developer forgot about it. By including the empty if, it says to the reader “yes I accounted for this and nothing should happen in this case”.

Certain coding standards require that all possible outcomes be explicitly accounted for in code. So code adhering to such a standard might look something like this.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)