Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# require parens around conditionals?

Tags:

syntax

c#

I was just reading an SO question on Python, and noticed the lack of parentheses in a for-loop. Looked nice to me, then I wondered: why does C# require them?

For example, I currently need to write:

if (thing == stuff) {
}

and

foreach (var beyonce in allthesingleladies) {
}

So I am wondering why I can't write:

if thing == stuff {
}

Is there a syntactic ambiguity in that statement that I am unaware of?

PS, funnily, braces can be optional for one-liners:

if (thing == stuff)
  dostuff();
like image 697
Matt Sherman Avatar asked Aug 14 '10 17:08

Matt Sherman


1 Answers

The system needs some way to know when the condition stops and the statement starts. That means that either parens around the condition are optional, or the braces around the statement are optional. The designers of C# chose to make the braces optional (in the event that there's a single statement).

Consider this:

if x == 12 - x == 3 ? x++ : x--;

A parser could be written that can tell where the condition ends and the statement starts, but requiring the parentheses makes it substantially easier. In the case of my example, the grammar indicates that the full statement is if (x == 12) { -x == 3 ? x++ : x--; }. However, you don't know that the - is the beginning of the statement until you hit the second ==, which is already 3 tokens into it.

Since correctly parsing such examples requires looking an arbitrary number of tokens ahead in the input stream (and it arguably makes the code harder for humans to read), there's a good reason for requiring the parens.

like image 105
Gabe Avatar answered Sep 20 '22 12:09

Gabe