Programming Languages – Why Require Parentheses Around Expressions in If and While?

cjavaprogramming-languagessyntax

Languages like C, Java, and C++ all require parenthesis around an entire expression when used in an if, while, or switch.

if (true) {
    // Do something
}

as opposed to

if true {
    // Do something
}

This seems odd to me because the parenthesis are redundant. In this example, true is a single expression on its own. The parenthesis do not transform its meaning in any way I know of. Why does this odd syntax exist and why is it so common? Is there a benefit to it I'm not aware of?

Best Answer

There needs to be some way of telling where the condition ends and the branch begins. There are many different ways of doing that.

In some languages, there are no conditionals at all, e.g. in Smalltalk, Self, Newspeak, Io, Ioke, Seph, and Fancy. Conditional branching is simply implemented as a normal method like any other method. The method is implemented on booleans objects and gets called on a boolean. That way, the condition is simply the receiver of the method, and the two branches are two arguments, e.g. in Smalltalk:

aBooleanExpression ifTrue: [23] ifFalse: [42].

In case, you are more familiar with Java, this is equivalent to the following:

aBooleanExpression.ifThenElse(() -> 23, () -> 42);

In the Lisp family of languages, the situation is similar: conditionals are just normal functions (actually, macros) and the first argument is the condition, the second and third argument are the branches, so they are just normal function arguments, and there is nothing special needed to delimit them:

(if aBooleanExpression 23 42)

Some languages use keywords as delimiters, e.g. Algol, Ada, BASIC, Pascal, Modula-2, Oberon, Oberon-2, Active Oberon, Component Pascal, Zonnon, Modula-3:

IF aBooleanExpression THEN RETURN 23 ELSE RETURN 42;

In Ruby, you can use either a keyword or an expression separator (semicolon or newline):

if a_boolean_expression then 23 else 42 end

if a_boolean_expression; 23 else 42 end

# non-idiomatic, the minimum amount of whitespace required syntactically
if a_boolean_expression
23 else 42 end

# idiomatic, although only the first newline is required syntactically
if a_boolean_expression
  23
else
  42
end

Go requires the branches to be blocks and doesn't allow expressions or statements, which makes the curly braces mandatory. Therefore, parentheses aren't required, although you can add them if you want; Perl6 and Rust are similar in this regard:

if aBooleanExpression { return 23 } else { return 42 }

Some languages use other non-alphanumeric characters to delimit the condition, e.g. Python:

if aBooleanExpression: return 23
else: return 42

The bottom line is: you need some way of telling where the condition ends and the branch begins. There are many ways of doing so, parentheses are just one of them.

Related Topic