Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shall brackets be used for one line conditional statements? [closed]

Tags:

java

c++

c

Apart from readability, are there any differences in performance or compile-time when a single-line loop / conditional statement is written with and without brakets?

For example, are there any differences between following:

if (a > 10) 
    a = 0;

and

if (a > 10)
{
    a = 0;
}

?

like image 326
Jay Avatar asked Dec 08 '22 19:12

Jay


2 Answers

Of course there is no difference in performance. But there is a difference in the possibility of introducing errors:

if (a>10)
  a=0;

If somebody extends code and writes later,

if (a>10)
  a=0;
  printf ("a was reset\n");

This will always be printed because of the missing braces. Some people request that you always use braces to avoid this kind of errors.

like image 169
pbhd Avatar answered Dec 11 '22 09:12

pbhd


Contrary to several answers, there is a finite but negligible performance difference at compile time. There is zero difference of any kind at runtime.

like image 36
user207421 Avatar answered Dec 11 '22 09:12

user207421