Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

The if-else Statement

Controls conditional branching.


if ( expression )
      statement1
[else
      statement2]

If the value of expression is nonzero, statement1 is executed. If the optional else is present, statement2 is executed if the value of expression is zero. expression must be of arithmetic or pointer type, or it must be of a class type that defines an unambiguous conversion to an arithmetic or pointer type. (For information about conversions, see Standard Conversions.)

In both forms of the if statement, expression, which can have any value except a structure, is evaluated, including all side effects. Control passes from the if statement to the next statement in the program unless one of the statements contains a break, continue, or goto.

The else clause of an if...else statement is associated with the closest previous if statement in the same scope that does not have a corresponding else statement.

For this sample to be unambiguous about if...else pairing, uncomment the braces.

// if_else_statement.cpp
#include <stdio.h>

int main() {
   int x = 0;
   if ( 1 )   // if statement #1
   // {
      if ( !x )   // if statement #2
         printf_s("!x\n");
      else   // paired with if statement #2
         printf_s("x\n");
   // }
}

Output

!x

Community Additions

ADD
Show:
© 2015 Microsoft