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

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like
operators in carbon language

Operators in Carbon Language

Table of Contents Hide ArithmeticBitwise & BitshiftComparisonConversionLogicalIndexingFunction CallPointerMoveConclusion We have a number of operators in Carbon language like – Arithmetic, Bitwise, BitShift, Comparison, Conversion, Logical, Indexing, function call, pointer, move…
View Post
functions in carbon language

Functions in Carbon Language

Table of Contents Hide IntroductionCode Example –Conclusion Functions in carbon language has the same role as in C, Php or any other functional language. It is used to separate a…
View Post
introduction to carbon language - what and why it is created

Introduction to Carbon Language

Table of Contents Hide IntroductionFeatures of Carbon LanguageWhy developed Carbon? Why not upgraded C++?Where Carbon could be used?Carbon is written in which language?Code Example Carbon Language is the successor to…
View Post