easy question: if, else if

May 11, 2009 at 7:49pm
Do I have to use braces after "if()", if I use "else if()" or "else"?
Which one is correct, or are they both correct?

1
2
3
4
5
6
7
if(x == 0)
 dosomething();
else if(x == 1)
{
 dosomething();
 andalsodothis():
}


1
2
3
4
5
6
7
8
9
if(x == 0)
{
 dosomething();
}
else if(x == 1)
{
 dosomething();
 andalsodothis():
}
Last edited on May 11, 2009 at 7:51pm
May 11, 2009 at 7:57pm
Both are technically correct. I've been on teams that prefer one over the other. I prefer the second one because there is less chance of screwing up when you need add something to the if clause and there is less noise when looking at code diffs.
May 11, 2009 at 7:58pm
They are both correct in this case. The general rule is that if you have more than one statement you must use braces. There are other situations where braces are needed in if/else constructs, so you are probably best to put them in all the time.
May 11, 2009 at 7:59pm
I thought so, but the first one is theoretically faster right?
Thanks!
May 11, 2009 at 8:00pm
Both are legal and behave as expected.

EDIT:
I thought so, but the first one is theoretically faster right?
No. They are equivalent.
Last edited on May 11, 2009 at 8:01pm
May 21, 2009 at 8:28pm
there correct, but you really should just put brackets around everything, because crazy shit can happen
Topic archived. No new replies allowed.