easy question: if, else if

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
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.
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.
I thought so, but the first one is theoretically faster right?
Thanks!
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
there correct, but you really should just put brackets around everything, because crazy shit can happen
Topic archived. No new replies allowed.