The language designers have chosen to make the curly braces in the following scenarios optional:
if (a)
b
while (a)
b
...
Why is the same not allowed in functions, like this?
int add(int a, int b)
return a + b;
Master C and Embedded C Programming- Learn as you go So we can omit curly braces only there is a single statement under if-else or loop. Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always.
In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
When you write single statement inside of loops or control statements then their is no need of braces. But when you want to write multiple line statements then you must have to use braces to tell compiler the scope of loop or control statements. otherwise it might give you unwanted output.
I'm sure this would mess up the grammar. For example there would be no difference between this empty function definition...
void empty()
{
;
}
...and this function declaration:
void empty();
I'm not sure that they did "choose" this. Rather, the ability ommit curly braces for if, while, for, etc. emerges as a natural consequence of the way they specified the grammar. The grammer forbids it for functions probably because of the old-style function declarations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With