Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you create a 1 statement function without curly braces?

Tags:

java

c++

c#

So, in most programming language, if you are using a loop or an if, you can do it without curly braces if there is only a single statement in it, example:

if (true)
    //Single statement;

for (int i = 0; i < 10; i++)
    //Single Statement

while (true)
    //Single statement

However, it doesn't work for functions, example:

void myFunction()
    //Single Statement

So, my question, why doesn't it work for functions?

like image 870
Shadow Avatar asked Sep 15 '14 11:09

Shadow


People also ask

Can we use if statement without curly braces?

Yes it is not necessary to use curly braces after conditions and loops (functions always need them) IF and only if there is just one statement following. In this case it automatically uses the next statement.

Do we need to put curly braces when there is only one statement in for loop?

If the number of statements following the for/if is single you don't have to use curly braces. But if the number of statements is more than one, then you need to use curly braces.

What will happen if a while statement does not have curly braces?

If there is no braces, only one statement is inside the loop. In your example above, the statement is an empty statement (noted with a lone semicolon).

When can curly braces be omitted from an if statement?

For historical reasons, we allow one exception to the above rules: if an if statement has no else or else if clauses, then the curly braces for the controlled statement or the line breaks inside the curly braces may be omitted if as a result the entire if statement appears on either a single line (in which case there ...


2 Answers

C++ needs it to disambiguate some constructs:

void Foo::bar() const int i = 5;

Now does the const belong to bar or i ?

like image 111
MSalters Avatar answered Nov 02 '22 15:11

MSalters


Because language grammar forbids you to do that.

The Java grammar defines a method as following:

MethodDeclaration:
    MethodHeader MethodBody

Methodbody as:

MethodBody:
    Block 
    ;

Which means either a Block (see below) or a single semicolon

Block:
    { BlockStatementsopt }

And a block as one or more statements within curly brackets.

However an if is defined as:

IfThenStatement:
    if ( Expression ) Statement

Where no block is needed after the closing ) and therefore a single line is ok.

Why they chose to define it that way? One can only guess.

Grammar can be found here: http://docs.oracle.com/javase/specs/jls/se7/html/index.html

like image 41
Frederick Roth Avatar answered Nov 02 '22 16:11

Frederick Roth