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
213
votes
6 answers

Can I use the range operator with if statement in Swift?

Is it possible to use the range operator ... and ..< with if statement. Maye something like this: let statusCode = 204 if statusCode in 200 ..< 299 { NSLog("Success") }
Jimmy
  • 10,427
  • 18
  • 67
  • 122
212
votes
5 answers

How to implement if-else statement in XSLT?

I am trying to implement an if -else statement in XSLT but my code just doesn't parse. Does anyone have any ideas? date:…
Funky
  • 12,890
  • 35
  • 106
  • 161
206
votes
12 answers

inline conditionals in angular.js

I was wondering if there is a way in angular to conditionally display content other than using ng-show etc. For example in backbone.js I could do something with inline content in a template like: <% if (myVar === "two") { %> show this<% } %> but in…
user1469779
  • 2,541
  • 4
  • 18
  • 21
203
votes
14 answers

One line if-condition-assignment

I have the following code num1 = 10 someBoolValue = True I need to set the value of num1 to 20 if someBoolValue is True; and do nothing otherwise. So, here is my code for that num1 = 20 if someBoolValue else num1 Is there someway I could avoid the…
bdhar
  • 21,619
  • 17
  • 70
  • 86
203
votes
7 answers

Python if not == vs if !=

What is the difference between these two lines of code: if not x == 'val': and if x != 'val': Is one more efficient than the other? Would it be better to use if x == 'val': pass else:
lafferc
  • 2,741
  • 3
  • 24
  • 37
203
votes
14 answers

Can I use if (pointer) instead of if (pointer != NULL)?

Is it safe to check a pointer to not being NULL by writing simply if(pointer) or do I have to use if(pointer != NULL)?
danijar
  • 32,406
  • 45
  • 166
  • 297
200
votes
14 answers

Checking for NULL pointer in C/C++

In a recent code review, a contributor is trying to enforce that all NULL checks on pointers be performed in the following manner: int * some_ptr; // ... if (some_ptr == NULL) { // Handle null-pointer error } else { // Proceed } instead…
Bryan Marble
  • 3,467
  • 5
  • 26
  • 29
198
votes
16 answers

Test if a string contains any of the strings from an array

How do I test a string to see if it contains any of the strings from an array? Instead of using if (string.contains(item1) || string.contains(item2) || string.contains(item3))
arowell
  • 2,271
  • 2
  • 15
  • 19
197
votes
10 answers

What is the effect of ordering if...else if statements by probability?

Specifically, if I have a series of if...else if statements, and I somehow know beforehand the relative probability that each statement will evaluate to true, how much difference in execution time does it make to sort them in order of probability?…
Carlton
  • 4,217
  • 2
  • 24
  • 40
193
votes
3 answers

Conditional import of modules in Python

In my program I want to import simplejson or json based on OS being Linux or Windows. I take the OS name as input from the user. Now, is it correct to do it with a condition like this? osys = raw_input("Press l for linux, w for Windows:") if (osys…
Tim
  • 1,971
  • 2
  • 12
  • 3
185
votes
23 answers

Advantage of switch over if-else statement

What's the best practice for using a switch statement vs using an if statement for 30 unsigned enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical.…
Zing-
  • 2,087
  • 2
  • 13
  • 12
180
votes
9 answers

Check if a value is within a range of numbers

I want to check if a value is in an accepted range. If yes, to do something; otherwise, something else. The range is 0.001-0.009. I know how to use multiple if to check this, but I want to know if there is any way to check it in a single if…
Sotiris
  • 38,986
  • 11
  • 53
  • 85
175
votes
15 answers

Is it a bad practice to use an if-statement without curly braces?

I've seen code like this: if(statement) do this; else do this; However, I think this is more readable: if(statement){ do this; }else{ do this; } Since both methods work, is this simply a matter of preference which to use or would…
jerebear
  • 6,503
  • 4
  • 31
  • 38
172
votes
21 answers

Assignment in an if statement

I have a class Animal, and its subclass Dog. I often find myself coding the following lines: if (animal is Dog) { Dog dog = animal as Dog; dog.Name; ... } For the variable Animal animal;. Is there some syntax that allows me to…
michael
  • 1,849
  • 2
  • 13
  • 5
172
votes
13 answers

Compare two columns using pandas

Using this as a starting point: a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']] df = pd.DataFrame(a, columns=['one', 'two', 'three']) which looks like one two three 0 10 1.2 4.2 1 15 70 0.03 2 8 5 0 I want…
Merlin
  • 24,552
  • 41
  • 131
  • 206