semicolonSeveral days ago I stumbled upon a problem EXPR2 in SPOJ. The problem could be very easy if this constraint didn’t exist: use only C/C++, Pascal, or Java, and there must not be any semicolons in the source code.

Well, after googling and thinking a little bit, I realized that this problem can be solved easily using C++. The main savior here is the if block construct.

Wrapping Statements

Every statement in C++ must be terminated with a semicolon. However, unlike other languages, almost all statements in C++ can be treated as expressions (and vice versa). So, we can wrap the statements inside if blocks, and there is no need to type any semicolons again.

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

To execute statements in sequence, simply put one statement inside the other. Make sure that each expression in the sequence evaluates to true (nonzero).

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

If the expression inside the if block returns void, the snippet above will give syntax errors, because there is no value to test. A simple solution is using the comma operator, with 1 as the right operand.

if (doSomething(), 1) {}

Variable Declarations

In C++, variable declarations can also be placed inside if, while, and for, and switch construct, provided it is initialized. And make sure the variable is initialized to a value other than zero so that the next statement can be executed.

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 cleverly manipulating the test condition in the loop construct.

goto statements can (or should) always be avoided by using more structured block constructs.

return statements in a non-void function can be avoided by making the function void and provide a pass-by-reference parameter as the output parameter.

The real question is: Is every C++ program can be converted such that it won’t contain any semicolons again?

  • Share/Bookmark

Enjoyed this article? Subscribe to our RSS feed for free!

Related posts:

Be the first to comment!

Leave a Reply