What does a semicolon mean after an "if"?

Asked

Viewed 322 times

1

I was analyzing a code and came across a semicolon after a if, which means using the semicolon after a if?

code:

int base_calc(int cb)
{
    if( cb < 30 ) {
        ;
    } else if( cb < 20 ) {
        cb = 30 - 1;
    } else {
        cb = 30;
    }

    return cb;
}
  • Command null, does nothing.

  • It may be a way of saying that the block is purposely empty (unlike a blank line that could suggest forgetfulness).

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

2

It is not after the if, the semicolon exists to close a statement, Like you always used in "end of line" (which in the background does not close the line, we say this informally, he close the command), including used in other points. If the command has nothing it encloses nothing, no problem at all (it is called Empty statement). If you do this, it’s the same:

int base_calc(int cb)
    if( cb < 30 ) {
    } else if( cb < 20 ) {
        cb = 30 - 1;
    } else {
        cb = 30;
    }
    return cb;
}

It was used there to make it clearer in the code that the intention is to create a block that does nothing. Note that my code gives less idea that there is something empty to be done there, it is not the end of the world, but you waste a little time to make sure that is it.

You can rewrite the code so you don’t need this. In C or C++ this is not often done because it is less efficient, the rewriting is usually better (although it is not always necessary all this efficiency.

Just be careful with the keys there. This does not give the same result:

int base_calc(int cb)
    if( cb < 30 )
        ;
    else if( cb < 20 )
        cb = 30 - 1;
    else
        cb = 30;
    return cb;
}

I put in the Github for future reference.

In this case the ; is closing the statement if and nothing further will be executed. Luckily there is a else if then it can’t be loose so it will give a syntax error in the compilation.

1

Ali is just saying that there is nothing. Put a ; without any expression before it’s like there’s nothing on that line.

Therefore,

if( cb < 30 ) {
    ;
}

// é a mesma coisa de
if( cb < 30 ) {

}

Some programmers do this to indicate that there should be something there, which will be implemented or simply skipped this condition and went straight to else. It’s not good practice to do that because it’s the same thing:

bool condicao = false;
if(condicao == true) {
    ;
} else {
    // ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.