Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to use braces or no braces for single-line if blocks? [closed]

What is better coding practice for single-line code blocks following an if statement - braces or no braces? Just to avoid too many "Well, it depends on what language you're using..." answers, let's say for C#. In other words, which is better:

if(somecondition)
{
  singleLineStatement;
}

Or

if(somecondition)
  singleLineStatement;
like image 403
Zann Anderson Avatar asked Nov 03 '10 14:11

Zann Anderson


People also ask

Can the curly brackets be used to enclose a single line of code?

90) Can the curly brackets { } be used to enclose a single line of code? While curly brackets are mainly used to group several lines of codes, it will still work without error if you used it for a single line.

Are braces necessary in one line statements in Java?

However it is highly recommended that you always use braces because if you (or someone else) ever expands the statement it will be required. This same practice follows in all C syntax style languages with bracing. C, C++, Java, even PHP all support one line statement without braces.

Do I need brackets for if statements?

If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.

When can curly braces be omitted from an if statement?

In the first case, the Line1 and Line2 both are in the if block. But in the second condition, the Line1 is in if block but Line2 is not in if block. So we can omit curly braces only there is a single statement under if-else or loop.


1 Answers

I think the consensus is to use braces. If you omit the braces there is a risk that someone will add an extra line without noticing the missing braces.

like image 135
Mark Byers Avatar answered Oct 03 '22 08:10

Mark Byers