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
292
votes
17 answers

Short form for Java if statement

I know there is a way for writing a Java if statement in short form. if (city.getName() != null) { name = city.getName(); } else { name="N/A"; } Does anyone know how to write the short form for the above 5 lines into one line?
Makky
  • 17,117
  • 17
  • 63
  • 86
276
votes
51 answers

How to avoid "if" chains?

Assuming I have this pseudo-code: bool conditionA = executeStepA(); if (conditionA){ bool conditionB = executeStepB(); if (conditionB){ bool conditionC = executeStepC(); if (conditionC){ ... } …
ABCplus
  • 3,981
  • 3
  • 27
  • 43
266
votes
6 answers

What is a good practice to check if an environmental variable exists or not?

I want to check my environment for the existence of a variable, say "FOO", in Python. For this purpose, I am using the os standard library. After reading the library's documentation, I have figured out 2 ways to achieve my goal: Method 1: if "FOO"…
265
votes
26 answers

Too many 'if' statements?

The following code does work how I need it to, but it's ugly, excessive or a number of other things. I've looked at formulas and attempted to write a few solutions, but I end up with a similar amount of statements. Is there a type of math formula…
TomFirth
  • 2,334
  • 4
  • 20
  • 31
254
votes
7 answers

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

I've seen Bash scripts test for a non-zero length string in two different ways. Most scripts use the -n option: #!/bin/bash # With the -n option if [ -n "$var" ]; then # Do something when var is non-zero length fi But the -n option isn't really…
AllenHalsey
  • 2,541
  • 3
  • 15
  • 3
254
votes
4 answers

Difference between if (a - b < 0) and if (a < b)

I was reading Java's ArrayList source code and noticed some comparisons in if-statements. In Java 7, the method grow(int) uses if (newCapacity - minCapacity < 0) newCapacity = minCapacity; In Java 6, grow didn't exist. The method…
dejvuth
  • 6,986
  • 3
  • 33
  • 36
252
votes
24 answers

Java String - See if a string contains only numbers and not letters

I have a string that I load throughout my application, and it changes from numbers to letters and such. I have a simple if statement to see if it contains letters or numbers but, something isn't quite working correctly. Here is a snippet. String…
RedHatcc
  • 3,016
  • 4
  • 16
  • 13
237
votes
5 answers

Negate if condition in bash script

I'm stuck at trying to negate the following command: wget -q --tries=10 --timeout=20 --spider http://google.com if [[ $? -eq 0 ]]; then echo "Sorry you are Offline" exit 1 This if condition returns true if I'm connected to the…
Sudh33ra
  • 2,675
  • 3
  • 15
  • 19
228
votes
7 answers

How to prevent ifelse() from turning Date objects into numeric objects

I am using the function ifelse() to manipulate a date vector. I expected the result to be of class Date, and was surprised to get a numeric vector instead. Here is an example: dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03',…
Zach
  • 29,791
  • 35
  • 142
  • 201
226
votes
5 answers

Can dplyr package be used for conditional mutating?

Can the mutate be used when the mutation is conditional (depending on the values of certain column values)? This example helps showing what I mean. structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4, 2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6,…
rdatasculptor
  • 8,112
  • 14
  • 56
  • 81
224
votes
18 answers

Pythonic way to avoid "if x: return x" statements

I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. def check_all_conditions(): x = check_size() if x: …
Bernard
  • 2,118
  • 2
  • 10
  • 9
224
votes
7 answers

Difference between single and double square brackets in Bash

I'm reading bash examples about if but some examples are written with single square brackets: if [ -f $param ] then #... fi others with double square brackets: if [[ $? -ne 0 ]] then start looking for errors in yourlog fi What is the…
rkmax
  • 17,633
  • 23
  • 91
  • 176
222
votes
14 answers

Putting an if-elif-else statement on one line?

Is there an easier way of writing an if-elif-else statement so it fits on one line? For example, if expression1: statement1 elif expression2: statement2 else: statement3 Or a real-world example: if i > 100: x = 2 elif i < 100: x…
Matt Elson
  • 4,177
  • 8
  • 31
  • 46
221
votes
4 answers

Why does this if-statement combining assignment and an equality check return true?

I've been thinking of some beginner mistakes and I ended up with the one on the if statement. I expanded a bit the code to this: int i = 0; if (i = 1 && i == 0) { std::cout << i; } I have seen that the if statement returns true, and it cout's i…
TehMattGR
  • 1,710
  • 2
  • 7
  • 19
218
votes
4 answers

Bash if statement with multiple conditions throws an error

I'm trying to write a script that will check two error flags, and in case one flag (or both) are changed it'll echo-- error happened. My script: my_error_flag=0 my_error_flag_o=0 do something..... if [[ "$my_error_flag"=="1" ||…
Simply_me
  • 2,840
  • 4
  • 19
  • 27