if, else (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

Operators (C++)

C++ Syntax

if ( <condition1> )  <statement1>
if ( <condition1> )  <statement1>;
 else  <statement2>;
if ( <condition1> )  <statement1>;
 else if ( <condition2> )  <statement2>;
 else  <statement3>;
if ( <condition1> )
{
  if ( <condition2> ) {
  <statement1>
  <statement2>
  }
  else <statement3>
}
else
  <statement4>

Description

Use if to implement a conditional statement.

You can declare variables in the condition expression. For example,

if (int val = func(arg))

is valid syntax. The variable val is in scope for the if statement and extends to an else block when it exists.

The condition statement must convert to a bool type. Otherwise, the condition is ill-formed.

When <condition> evaluates to true, <statement1> executes.

If <condition> is false, <statement2> executes.

The else keyword is optional, but no statements can come between an if statement and an else.

The #if and #else preprocessor statements (directives) look similar to the if and else statements, but have very different effects. They control which source file lines are compiled and which are ignored.

See Also