Files
carbon-lang/docs/design/control_flow/conditionals.md
T
Aadarsh Raj 4e9e43a109 some issues in readme-file, replacing orange with apple (#2656)
**### There is issue in conditionals.md readme file** 
**In example of fruits conditionals** 
                            **there are fruits.IsGreen() if it is False then continue. 
                            if it is True then print "Apple" but in readme file there is "Orange"** 


I replaced "Orange" with "Apple" because in example there is "Apple" 
                    ```carbon
                                if (fruit.IsYellow()) {
                                  Print("Banana!");
                                } else if (fruit.IsOrange()) {
                                  Print("Orange!");
                                } else if (fruit.IsGreen()) {
                                  Print("Apple!");
                                } else {
                                  Print("Vegetable!");
                                }
                       fruit.Eat();
                        ```
2023-03-06 08:43:13 -08:00

2.4 KiB

Conditionals

Table of contents

Overview

if and else provide conditional execution of statements. Syntax is:

if (boolean expression ) { statements }

[ else if ( boolean expression ) { statements } ] ...

[ else { statements } ]

Only one group of statements will execute:

  • When the first if's boolean expression evaluates to true, its associated statements will execute.
  • When earlier boolean expressions evaluate to false and an else if's boolean expression evaluates to true, its associated statements will execute.
    • ... else if ... is equivalent to ... else { if ... }, but without visible nesting of braces.
  • When all boolean expressions evaluate to false, the else's associated statements will execute.

When a boolean expression evaluates to true, no later boolean expressions will evaluate.

Note that else if may be repeated.

For example:

if (fruit.IsYellow()) {
  Print("Banana!");
} else if (fruit.IsOrange()) {
  Print("Orange!");
} else if (fruit.IsGreen()) {
  Print("Apple!");
} else {
  Print("Vegetable!");
}
fruit.Eat();

This code will:

  • Evaluate fruit.IsYellow():
    • When True, print Banana! and resume execution at fruit.Eat().
    • When False, evaluate fruit.IsOrange():
      • When True, print Orange! and resume execution at fruit.Eat().
      • When False, evaluate fruit.IsGreen():
        • When True, print Apple! and resume execution at fruit.Eat().
        • When False, print Vegetable! and resume execution at fruit.Eat().

Alternatives considered

References