Why do { } while(condition); needs semicolon at the end of it but while(condition) {} doesn't?

s4eed picture s4eed · Feb 20, 2013 · Viewed 8.4k times · Source

I always have problem with placing ; at the end of while or not placing it at the end of do while loops. So what's the reason? Why

int numItemsToProcess = 3;  
while(numItemsToProcess > 0)  
{  
    // process an item  
    numItemsToProcess--;  
} 

doesn't need ; at the end but

do  
{  
    numItemsToProcess --;
} while (numItemsToProcess > 0);  

does? Maybe the reason is not too important. but when you know the reason you can remember where to put ;.

Answer

Some programmer dude picture Some programmer dude · Feb 20, 2013

You put semicolon after all statements, except the block statement. This is the reason that you place it after the while in do while, but not after the block in the while {...}.

You also use it to terminate almost all declarations. The only exceptions I can think about at the moment is function bodies, and namespace bodies in C++.