· by ·

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.

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!

")) {}

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)) {} }

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?