Different ways of writing the “if” statement [clos

2020-05-18 11:38发布

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”;
}

Similar question:

Why is it considered a bad practice to omit curly braces?

标签: c#
20条回答
我命由我不由天
2楼-- · 2020-05-18 12:11

None of the above.

If my execution block only has one line (even if it's a huge for statement) then I don't use braces, but I do indent it, similar to #3

if (num > 3)
     print "num is greater than 3";
else
     print "num is not greater than 3";

An example with multiple statements that do not need curly braces:

if (num > 3)
    for (int i = 0; i < 100)
        print i + "\n";
else
    print "booya!";

That said, Jon Skeet's response in this question is the best

查看更多
劫难
3楼-- · 2020-05-18 12:12

I prefer 4 myself, but I think 2 is definitely good too.

查看更多
登录 后发表回答