Write C++ without Semicolons!

One day I encountered a cool problem EXPR2 in SPOJ. The problem would have been very easy to solve if this constraint were not exist: use only C/C++, Pascal, or Java, and there must not be any semicolons in the source code.

I wondered how this problem can be solved. Doesn’t the four languages enforce us to type a semicolon after every statement? After googling and thinking a little bit, I found a solution. This is indeed can be solved in C++ without any semicolons. Our savior here is the if block statement.


We know that every statement in C++ must end with a semicolon. However, unlike other languages, almost all statements in C++ can be treated as expressions. So, if we place the statement inside an if statement with a blank pair of parentheses, we don’t have to end it with a semicolon anymore.

if (a = 1) {}
if (printf("Hello, world!\n")) {}

If we want to call a function that returns void, we cannot use that trick, as void functions are not expressions. But it can be remedied using the not so famous comma operator, with any value in the right hand side of the operator.

if (foo(), 1) {}

Variable Declaration

In C++, variable declarations can be placed inside if, while, for, and switch blocks, provided the variables are initialized. It must be initialized with a nonzero value so that the execution can continue into the block.

if (int N = 1) {
    if (scanf("%d", &N)) {}
    if (printf("%d\n", N)) {}

break, continue, goto, and return Statements

break and continue statements can always be avoided by manipulating the conditional expression in the corresponding loop.

goto statement can be avoided by using more structured block controls.

return statement in a non-void function can be cleverly avoided by making the function void and providing a by-reference parameter that acts as the return value.

So, now you can solve the problem yourself, can’t you?

About Ashar Fuadi

Ashar Fuadi is a competitive programmer from University of Indonesia. He loves to code, especially for TopCoder SRM, Codeforces, and ICPC.
Follow Ashar on Google+ and Twitter.


  1. Santiago says:

    Thanks! very useful!

  2. haha, ada juga ternyata problem beginian.

  3. Raja Sriram says:

    You can declare the variables as passing arguments to main function..
    for ex:-
    int main(int a,int b,float c)
    works well 🙂

  4. thnx…it was useful….enjoyed solving the problem too.. 😀

  5. Checkout this repository,, A minesweeper game implemented in C without use any of semicolons.

  6. what do you mean by “almost all statements in C++ can be treated as expressions”?
    the expression “a = 1” evaluates to 1 and is still not a statement without the semicolon, so I still do not understand why “if (a = 1) {}” does the assignment as well with no semicolon…

Speak Your Mind