I have seen different ways of writing an if
statement.
Which one do you prefer and why?
Example 1:
if (val % 2 == 1){output = “Number is odd”;}else{output = “Number is even”;}
Example 2:
if (val % 2 == 1)
{
output = “Number is odd”;
}
else
{
output = “Number is even”;
}
Example 3:
if (val % 2 == 1)
output = “Number is odd”;
else
output = “Number is even”;
Example 4:
if (val % 2 == 1){
output = “Number is odd”;
} else {
output = “Number is even”;
}
I use version 2.
One reason to use curly braces becomes more clear if you don't have an else.
If you then need to add another line of code, you are less likely to have an issue:
Without the braces you might have done this:
I personally prefer 3. The extra curly braces just add too much unnecessary visual noise and whitespace.
I can somewhat see the reasoning for 2/4 to reduce bugs, but I have personally never had a bug because thinking extra lines were inside an if statement. I do use C# and visual studio so my code always stays pretty well formatted. This could however be a problem if I was a more notepad style programmer.
It is more important to be consistent than to select the best.
These styles have different advantages and drawbacks, but none is as bad as mixing them within a project or even a compilation unit or within a function.
Ternary operator is the obvious choice for this specific code. For simple single statement
if/else
's that can't be otherwise expressed, I'd prefer a properly indented case 3:I understand the motivation behind "always use braces", but I've personally never been bitten by their omission (OK, once. With a macro.)
From the above styles, I'd pick (2). (4) would be ok if "properly" indented.
(1) I'd attribute to a young developer who hopefully will grow out of "compact code", or someone who can't afford a decent monitor. Still, I'd go with it if it was the local style.
Version 2. I always include the brackets because if you ever need to put more than one line under the conditional you won't have to worry about putting the brackets in at a later date. That, and it makes sure that ALL of your if statements have the same structure which helps when you're scanning code for a certain if statement.
I use version 2.
For cases like this, there's also the conditional operator:
If you're definitely going to use an "if" I'd use version 2 or version 4, depending on the rest of your bracing style. (At work I use 4; for personal projects I use 2.) The main thing is that there are braces even around single statements.
BTW, for testing parity it's slightly quicker to use: