Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are curly braces in functions not optional in C-style languages?

Tags:

c

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;
like image 756
Overv Avatar asked Oct 23 '12 15:10

Overv


People also ask

Are curly brackets necessary in C?

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.

Why curly braces are used in C program?

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.

Why we use curly parenthesis not any other brackets?

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.

Why do we need to place braces even if they are not required in programming?

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.


2 Answers

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();
like image 54
Robert Cooper Avatar answered Sep 28 '22 02:09

Robert Cooper


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.

like image 38
Peter Ruderman Avatar answered Sep 28 '22 03:09

Peter Ruderman