Ternary Operator (If expressions) in Carbon

Total
0
Shares
ternary operator if expression in carbon

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 condition then value1 else 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