Namespaces
Variants
Views
Actions

if statement

From cppreference.com
< c‎ | language
Revision as of 20:22, 2 November 2012 by P12bot (Talk | contribs)

Conditionally executes code.

Used where code needs to be executed only if some condition is present.

Contents

Syntax

if ( Template:sparam ) Template:sparam
if ( Template:sparam ) Template:sparam else Template:sparam

Explanation

Template:sparam shall be an expression, convertible to bool.

If it evaluates to true, control is passed to Template:sparam, Template:sparam (if present) is not executed.

Otherwise, control is passed to Template:sparam, Template:sparam is not executed.

Keywords

if, else

Example

#include <stdio.h>
 
int main()
{
    int i = 2;
    if (i > 2) {
        printf("first is true\n");
    } else {
        printf("first is false\n");
    }
 
    i = 3;
    if (i == 3) printf("i == 3\n");
 
    if (i != 3) printf("i != 3\n");
    else        printf("i != 3 is false\n");
}

Output:

first is false
i == 3
i != 3 is false