Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways of writing the "if" statement [closed]

Tags:

c#

People also ask

How do you close an if statement?

An IF statement is executed based on the occurrence of a certain condition. IF statements must begin with the keyword IF and terminate with the keyword END.

What are the three types of IF statement?

There are three forms of IF statements: IF-THEN , IF-THEN-ELSE , and IF-THEN-ELSIF . The simplest form of IF statement associates a Boolean expression with a sequence of statements enclosed by the keywords THEN and END IF . The sequence of statements is executed only if the expression returns TRUE .

How do you write an if statement?

An if statement is written with the if keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets. In short, it can be written as if () {} .


For cases like this, there's also the conditional operator:

output = (val % 2 == 1) ? "Number is odd" : "Number is even";

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:

if ((val & 1) == 1)

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.

One reason to use curly braces becomes more clear if you don't have an else.

if(SomeCondition)
{
  DoSomething();
}

If you then need to add another line of code, you are less likely to have an issue:

if(SomeCondition)
{ 
  DoSomething();
  DoSomethingElse();
}

Without the braces you might have done this:

if(SomeCondition)
   DoSomething();
   DoSomethingElse();

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.


I prefer #2. Easy readability.