Questions tagged [if-statement]

An "if" statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If statements are also commonly also called conditionals. When using this tag please also include an appropriate language tag, such as e.g. "java" if your question is language-specific.

An if statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If-statements are also commonly known as conditionals.

When using this tag please also include an appropriate language tag, such as e.g. if your question is language-specific.


Basic Syntax

The if statement has the following syntax:

if <condition>
then
     <statement-1>
else
     <statement-2>

<condition> may be parenthesized (as it is in JavaScript), the keyword then may be omitted (Python, C-like languages, JavaScript and others).

The else section is optional in most languages.

An example if statement in JavaScript:

var myVariable = 100;

if (myVariable >= 20) {
    console.log('My variable is greater than or equal to 20!');
} else {
    console.log('My variable is less than 20!');
}

if-else statements may also be nested, where another if may appear in if statement, and/or in else statement. For example:

if ( number1 > 20 )
   if ( number2 > 50 )
      print('Both numbers satisfy condition')
   else
      print('Second number doesn't satisfy condition')
else
   if( number2 > 50 )
      print('Only Second number satisfies condition')
   else
      print('None of the two numbers satisfy condition')

else+if is used to chain if statements:

if ( number > 20 )
     print('Greater than 20')
else+if ( number > 10 )
     print('Greater than 10')
else
     print('Less than 11')

else+if statements may simply be an else statement followed by an if (e.g else if; done in JavaScript and many C-like languages), or a special keyword such as elif (Python), or elsif (Perl).


As a ternary operator

In C and C-like languages, conditional expressions can take the form of a ternary operator called the conditional expression operator, ?:, which follows this template:

(condition)?(evaluate if condition was true):(evaluate if condition was false)

In Python, if is used explicitly, and the ordering is slightly different:

(evaluate if condition was true) if (condition) else (evaluate if condition was false)

An example of the ternary operator in JavaScript:

var myVariable = 100;

myVariable>20 ? console.log('Greater than 20!') : console.log('Less than or equal to 20!');

See also:

61703 questions
7
votes
5 answers

Best practices for Python if-elif-elif-elif when dispatching requests

I have 5 sets of request's categories defined as python dicts, for example: category1 = {'type1', 'type2', 'type3'} category2 = {'type4', 'type5'} category3 = {'type6', 'type7', 'type8', 'type9'} category4 = {'type10', 'type11'} category5 =…
Sergio Ayestarán
  • 5,590
  • 4
  • 38
  • 62
7
votes
4 answers

java: A long list of conditions , what to do?

I need suggestion for the right approach to apply conditions in Java. I have 100 conditions based on which I have to change value of a String variable that would be displayed to the user. an example condition: a<5 && (b>0 && c>8) && d>9 || x!=4 More…
Prateek
  • 3,923
  • 6
  • 41
  • 79
7
votes
4 answers

The order of expressions in an if statement

Possible Duplicate: What is the difference between these (bCondition == NULL) and (NULL==bCondition)? Javascript minification of comparison statements Ive been writing my if statements like this: if(variable1 === 1){} if(variable2 >…
Jimmery
  • 9,783
  • 25
  • 83
  • 157
7
votes
14 answers

What is efficient to check: equal to or not equal to?

I was wondering, if we have if-else condition, then what is computationally more efficient to check: using the equal to operator or the not equal to operator? Is there any difference at all? E.g., which one of the following is computationally…
jsist
  • 5,223
  • 3
  • 28
  • 43
7
votes
4 answers

PHP - Concatenate if statement?

I want to concatenate in the middle of an echo to write an if statement, is this possible? Here is what I have. echo "
  • Home
  • ";
    Necro.
    • 987
    • 6
    • 17
    • 29
    7
    votes
    5 answers

    c# short if statement not working with int? (int=null)

    I am trying to shorten my code by using short-if: int? myInt=myTextBox.Text == "" ? null : Convert.ToInt32(myTextBox.Text); But I'm getting the following error: Type of conditional expression cannot be determined because there is no implicit…
    YaakovHatam
    • 2,314
    • 2
    • 22
    • 40
    7
    votes
    6 answers

    Replacing If Else unique conditional nested statements

    Switch case statements are good to replace nested if statements if we have the same condition but different criteria. But what is a good approach if those nested if statements all have different and unique conditions? Do I have any alternate options…
    EP2012
    • 343
    • 1
    • 7
    • 13
    7
    votes
    2 answers

    Mathematica If-then vs. Implies

    I am new to Mathematica(v8) and am using it to program propositional logic. I'm wondering what the difference is between the If and the Implies operators. For example, both If[p,q] and Implies[p,q] return q for p=True (as expected). But when I try…
    QuietThud
    • 351
    • 1
    • 12
    7
    votes
    7 answers

    Prompt JavaScript If Else Unexpected Token else

    I'm teaching myself JavaScript using Code Academy and I'm trying to make some simple code so that when prompt asks a question, the user reply gives a response. example. prompt says "what's your favourite colour?" user says "blue" response "that's…
    dansboxers
    • 73
    • 1
    • 1
    • 4
    7
    votes
    3 answers

    Python if Statement Invalid Syntax!? Why?

    while x < len(Hand): while y < len(Hand): if Hand[x][0] == Hand[y][0] and y != x: sameRank += 1 y += 1 x += 1 It highlights a space right before the "if" and says syntax error...Makes no sense.
    user1713330
    7
    votes
    7 answers

    Performance or style difference between "if" and "if not"?

    Is there a performance difference or style preference between these two ways of writing if statements? It is basically the same thing, the 1 condition will be met only once while the other condition will be met every other time. Should the…
    ss41153
    • 71
    • 2
    7
    votes
    3 answers

    If Statement VHDL

    Can some one explain why the golden rule when writing VHDL is that the if-then-else statement must be in a process. Is it because inside the process, the statements are executed sequentially, while outside they're not.
    user1533465
    • 71
    • 1
    • 1
    • 3
    7
    votes
    7 answers

    Cost of compound if/or versus try/catch in Java 6

    We currently have the following compound if statement... if ((billingRemoteService == null) || billingRemoteService.getServiceHeader() == null || !"00".equals(billingRemoteService.getServiceHeader().getStatusCode()) ||…
    David Nedrow
    • 1,098
    • 1
    • 9
    • 26
    7
    votes
    7 answers

    If statement simplification in C#

    I have a line of code that looks like this: if (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float) Is it possible to write something more elegant than this? Something like: if (obj is byte, int, long) I…
    Jon Tackabury
    • 47,710
    • 52
    • 130
    • 168
    7
    votes
    4 answers

    PHP: If a equals b or c or d

    Possible Duplicate: Short hand to do something like: if($variable == 1 || $variable == “whatever” || $variable == '492') . Is this if ($a==b||$a==c||$a==$d){ ... the shortest way to describe this logic. I am thinking about something like if…
    Martin
    • 1,193
    • 3
    • 12
    • 24