Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do C languages require parens around a simple condition in an if statement?

People also ask

Why we use simple if statement in C?

Working of 'simple if' statementThe statement inside the if block are executed only when condition is true, otherwise not. If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute.

Are parenthesis mandatory around the condition in an if statement?

So, to put it short: don't use parentheses for wrapping the condition, but use them whenever it increases readability with complex conditions.

What is the purpose of parentheses in programming?

In many computer programming languages, parentheses have a special purpose. For example, they are frequently used to enclose arguments to functions and methods. In languages such as Lisp, parentheses define an s-expression. In regular expressions, parentheses are used for pattern grouping and capturing.

DO IF statements need parentheses C++?

They are optional. That is just how it is. If you don't use braces to group multiple statements into one, then only the first statement following the for or if preamble is considered part of that construct.


If there are no brackets around expressions in if constructs, what would be the meaning of the following statement?

if x * x * b = NULL;

Is it

if (x*x)
    (*b) = NULL;

or is it

if (x)
    (*x) * b = NULL;

(of course these are silly examples and don't even work for obvious reasons but you get the point)

TLDR: Brackets are required in C to remove even the possibility of any syntactic ambiguity.


Tell me how to interprit the following:

if x ++ b;

Looks silly but...

if( x ) ++b;

or

if( x++ ) b;

or perhaps "x" has an overloaded operator then...

if( x ++ b){;}

Edit:

As Martin York noted "++" has a higher precedence which is why I've had to add the operator overloading tidbit. He's absolutely right when dealing with modern compilers up until you allow for all that overloading goodness which comes with C++.


I think a better question would be "why would we want such a thing?" than "why don't we have it?". It introduces another otherwise unnecessary edge case into the lexer, just so you can avoid typing 4 extra characters; and adds complexity to the spec by allowing exceptions to a simple syntax that already supports all possible cases just fine. Not to mention toes the line of ambiguity, which in a programming language doesn't have much value.


One other possible thing to keep in mind: C was created at a time when tape storage was common, so random seek or going backwards through the current file or even other files was not really feasible (which also explains why you have to put some stuff (i.e. forward declarations) before other stuff (i.e. usage of functions) even though the compiler should be able to figure it out on it's own).