Ternary operators are generally used to return a value based on conditions in a single statement. This prevents unnecessary variable declarations and memory consumption. In Carbon we have if expressions
in place of usual ?:
ternary notations.
Introduction
An if
expression is an expression of the form:
if
conditionthen
value1else
value2
The condition is converted to a bool
value in the same way as the condition of an if
statement.
The value1 and value2 are implicitly converted to their common type, which is the type of the if
expression.
Code Example
var a: i32 = 50; var b: i32 = 60; var c: i32 = if a < b then a else b; // c = 50 var d: i32 = (if a > b then a - b else b - a) * 10; // d = (b - a) * 10 = (60 - 50) * 10 = 10 * 10 = 100
Carbon Language Series
- Introduction to Carbon Language.
- How to define variables in Carbon.
- Primitive Types – Bool, Int, Float, String
- Tuple in Carbon
- Struct in Carbon
- Pointers in Carbon
- Operators in Carbon Language
- Conditions & Control Flow in Carbon
- Ternary Operator (if expression) in Carbon
- Switch conditional in Carbon using Match
- Loops in Carbon
- Functions in Carbon