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
171
votes
3 answers

Using multiple let-as within a if-statement in Swift

I'm unwrapping two values from a dictionary and before using them I have to cast them and test for the right type. This is what I came up with: var latitude : AnyObject! = imageDictionary["latitude"] var longitude : AnyObject! =…
suntoch
  • 1,834
  • 2
  • 13
  • 13
170
votes
14 answers

How to do if-else in Thymeleaf?

What's the best way to do a simple if-else in Thymeleaf? I want to achieve in Thymeleaf the same effect as

Hello!

Maciej Ziarko
  • 11,494
  • 13
  • 48
  • 69
167
votes
8 answers

How to use OR condition in a JavaScript IF statement?

I understand that in JavaScript you can write: if (A && B) { do something } But how do I implement an OR such as: if (A OR B) { do something }
sadmicrowave
  • 39,964
  • 34
  • 108
  • 180
163
votes
8 answers

How to use if - else structure in a batch file?

I have a question about if - else structure in a batch file. Each command runs individually, but I couldn't use "if - else" blocks safely so these parts of my programme doesn't work. How can I do make these parts run? Thank you. IF %F%==1 IF %C%==1…
eponymous
  • 2,090
  • 5
  • 23
  • 29
162
votes
12 answers

How to do one-liner if else statement?

Please see https://golangdocs.com/ternary-operator-in-golang as pointed by @accdias (see comments) Can I write a simple if-else statement with variable assignment in go (golang) as I would do in php? For example: $var = ( $a > $b )? $a:…
thoroc
  • 3,291
  • 2
  • 27
  • 34
160
votes
5 answers

Count with IF condition in MySQL query

I have two tables, one is for news and the other one is for comments and I want to get the count of the comments whose status has been set as approved. SELECT ccc_news . *, count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id,…
user1163513
  • 4,087
  • 7
  • 24
  • 25
157
votes
10 answers

&& (AND) and || (OR) in IF statements

I have the following code: if(!partialHits.get(req_nr).containsKey(z) || partialHits.get(req_nr).get(z) < tmpmap.get(z)){ partialHits.get(z).put(z, tmpmap.get(z)); } where partialHits is a HashMap. What will happen if the first statement…
Azimuth
  • 2,599
  • 4
  • 26
  • 33
155
votes
15 answers

How to shorten my conditional statements

I have a very long conditional statement like the following: if(test.type == 'itema' || test.type == 'itemb' || test.type == 'itemc' || test.type == 'itemd'){ // do something. } I was wondering if I could refactor this expression/statement into…
FlyingCat
  • 14,036
  • 36
  • 119
  • 198
153
votes
9 answers

Why can't R's ifelse statements return vectors?

I've found R's ifelse statements to be pretty handy from time to time. For example: ifelse(TRUE,1,2) # [1] 1 ifelse(FALSE,1,2) # [1] 2 But I'm somewhat confused by the following behavior. ifelse(TRUE,c(1,2),c(3,4)) # [1]…
Christopher DuBois
  • 42,350
  • 23
  • 71
  • 93
152
votes
8 answers

C++, variable declaration in 'if' expression

What's going on here? if(int a = Func1()) { // Works. } if((int a = Func1())) { // Fails to compile. } if((int a = Func1()) && (int b = Func2())) ) { // Do stuff with a and b. // This is what I'd really like to be able to…
Neutrino
  • 8,496
  • 4
  • 57
  • 83
152
votes
8 answers

Better to 'try' something and catch the exception or test if it's possible first to avoid an exception?

Should I test if something is valid or just try to do it and catch the exception? Is there any solid documentation saying that one way is preferred? Is one way more pythonic? For example, should I: if len(my_list) >= 4: x = my_list[3] else: …
chown
  • 51,908
  • 16
  • 134
  • 170
151
votes
4 answers

Regex matching in a Bash if statement

What did I do wrong here? Trying to match any string that contains spaces, lowercase, uppercase, or numbers. Special characters would be nice too, but I think that requires escaping certain characters. TEST="THIS is a TEST title with some numbers…
Atomiklan
  • 5,164
  • 11
  • 40
  • 62
150
votes
12 answers

If condition A is matched, condition B needs to be matched in order to do action C

My question is: if (/* condition A */) { if(/* condition B */) { /* do action C */ } else /* ... */ } else { /* do action C */ } Is it possible to just write the code of action C one time instead of twice? How…
148
votes
16 answers

IF statement: how to leave cell blank if condition is false ("" does not work)

I would like to write an IF statement, where the cell is left blank if the condition is FALSE. Note that, if the following formula is entered in C1 (for which the condition is false) for example: =IF(A1=1,B1,"") and if C1 is tested for being blank…
Mayou
  • 8,498
  • 16
  • 59
  • 98
147
votes
0 answers

Does inverting the "if" improve performance?

I've been using ReSharper for a while now and sometimes it suggests that I invert the if. I guess an example would be a better explanation of my situation: public void myfunction(int exampleParam){ if(exampleParam > 0){ //Do something…
Nasreddine
  • 36,610
  • 17
  • 75
  • 94