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

C# ?: Expression

I have a function with multiple if's (THIS IS NOT THE ACTUAL CODE) if(n == 1) m = 1; if(n == 2) m = 2; if(n == 3) m = 3; Instead of that I wanted to do make them all into ?: expression : (n == 1) ? m = 1; But it says that its expecting a…
user779444
  • 1,365
  • 4
  • 21
  • 38
6
votes
4 answers

Is there a better way to get visual studio to ignore try/catch in debug mode

I want the designer to catch the error when I am debugging and I want the user to see my friendly message if an error occurs for them. I know I can acomplish this with the following: #If Debug=False Then Try #End If 'some code here #If…
Chris
6
votes
2 answers

Should one use `if ($a != NULL)` or `if ($a !== NULL)` to control program flow?

This is perhaps a painfully basic question to answer, but I'm wondering about performance issues regarding using PHP's if identical !== versus if equal != to control flow. Consider the following trivial PHP function:
msanford
  • 11,803
  • 11
  • 66
  • 93
6
votes
1 answer

Looking for a more efficient ifelse()

While R's ifelse is incredibly handy, it does have a particular shortcoming: in the call ifelse(test, yes, no) all elements of yes and no are evaluated, even those that will be thrown away. This is rather wasteful if you're using it in the middle of…
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
6
votes
5 answers

Performance of Overriding vs. if-statement

I'm extending and improving a Java application which also does long running searches with a small DSL (in detail it is used for Model-Finding, yes it's in general NP-Complete). During this search I want to show a small progress bar on the console.…
H-Man2
  • 3,169
  • 20
  • 19
6
votes
3 answers

Shorter way to check multiple or conditions

Is there any easier way of checking one variables value against several others? Currently I'm using code like this: if(a[i] == a[i-13] || a[i] == a[i+13] || a[i] == a[i-1] || a[i] == a[i+1]){ //my code } Now, is there a shorter way to do this? I…
Some Guy
  • 15,854
  • 10
  • 58
  • 67
6
votes
4 answers

IF-Statement in SQLite: update or insert?

I Can't run this query with SQLite if 0<(select COUNT(*) from Repetition where (Word='behnam' and Topic='mine')) begin update Repetition set Counts=1+ (select Counts from Repetition where (Word='behnam' and Topic='mine')) end else begin insert…
Behnam-s
  • 131
  • 1
  • 1
  • 9
6
votes
5 answers

Switch Statement in C

I have the following if-statements: if (strcmp(registerName, "zero")) return 00000; else if (strcmp(registerName, "at")) return 00001; else if (strcmp(registerName, "v0")) return 00010; else if…
darksky
  • 20,411
  • 61
  • 165
  • 254
6
votes
3 answers

Greeting program

I have been learning how to program in Python using the book "Python the Absolute Beginners Guide." The problem I am having is that when using eclipse-pydev it won't allow me to use the if statement. Here is the code I have written... name =…
Kbob1998
  • 77
  • 1
  • 1
  • 6
6
votes
4 answers

how to deal with missing values in ifelse function julia

I am using Julia and I got a dataframe with 42 values, of which 2 are missing. This values are prices that go from 0.23 to 0.3 I am trying to get a new column that tells if its cheap or expensive by a ifelse statement. the ifelse should…
Jorge Paredes
  • 996
  • 7
  • 13
6
votes
1 answer

For loop that adds and deducts from pandas columns

So I have this df SUPPLIER PRODUCTID STOREID BALANCE AVG_SALES TO_SHIP SUP1 P1 STR1 50 5 18 SUP1 P1 STR2 6 7 18 SUP1 P1 STR3 74 4 …
its.kcl
  • 123
  • 7
6
votes
5 answers

Whats wrong with my simple If Else?

Im new to RoR/Ruby and i cant seem to get the simplest thing to work. (trust me, ive search google and reread docs, i dont know what wrong) So in my main view, I added the following: <%= if 1>2 %> <%= print "helllloooo" %> <%= else %> <%=…
Jonah Katz
  • 5,230
  • 16
  • 67
  • 90
6
votes
3 answers

Checking for membership in an Erlang guard

What is the simplest way to write an if statement in Erlang, where a part of the guard is member(E, L), i.e., testing if E is a member of the list L? The naive approach is: if ... andalso member(E,L) -> ... end But is does not work becuase, if I…
Little Bobby Tables
  • 5,261
  • 2
  • 39
  • 49
6
votes
2 answers

How to use ifelse inside map function in R

I am having problems with this ifelse sentence inside map function: df<-list(mtcars,mtcars) All I want to do is to organize each dataframe of this list this way:slice(x,c(n(),2:(n()-1),1)) map(df, ~ slice(.x,c(n(),2:(n()-1),1))) # it works…
Laura
  • 675
  • 10
  • 32
6
votes
2 answers

Variable before or after value in IF statement

Is there a difference between these two statements: if ($a == 'hello') { ... } and if ('hello' == $a) { ... } I've noticed applications like Wordpress tend to use the latter, whereas I usually use the former. I seem to remember reading something a…
steveneaston
  • 259
  • 1
  • 4
  • 10
1 2 3
99
100