Recent changes Random page
GAMING
Technology
 
Gaming
Entertainment
Science Fiction
Biggest wikis
Hobbies
Music
See more...

If statement

From Programmer's Wiki

Jump to: navigation, search
 

If statements allow different actions to be taken depending on a condition. An if statement consists of a condition, a then clause, and an else clause. If the condition is true then the then clause is executed, otherwise the else clause is executed. If no else clause is supplied, then nothing is executed if the condition is false. The condition consists of an expression which will be evaluated at runtime and compared with the value true. The then and else clauses consist of zero or more statements.

Contents

[edit] Typical Use

Typical syntax is

if criterion1
   action1
else 
   if criterion2
       action2 
   else
       action3

When the purpose of the if statement is to return one of two values, depending on a condition, the Ternary Operator may be used in some languages (e.g. C, awk) as follows:

condition ? expression1 : expression2;

The ternary operator returns the value of whichever action it takes, making it a useful function. In this way, it differs from the if statement, which does not (in most languages) return a value. The ternary operator example above is similar but (not quite identical) to:

if condition
   return(expression1)
else
   return(expression2)

When several if statements are used in a cascade to choose between several options, a Switch Statement might be worth considering as a more readable and maintainable replacement.

[edit] Code Snippets

[edit] C

[edit] Ruby

[edit] Visual Basic

If booleanExpression then
   statement1;
Else
   statement2;
End If


[edit] C#

if( booleanExpression )
   statement1;
else
   statement2;

[edit] Python

[edit] TSQL

[edit] See Also

Rate this article:
Share this article: