Files
carbon-lang/docs/design/expressions

Expressions

Table of contents

Overview

Expressions are the portions of Carbon syntax that produce values. Because types in Carbon are values, this includes anywhere that a type is specified.

fn Foo(a: i32*) -> i32 {
  return *a;
}

Here, the parameter type i32*, the return type i32, and the operand *a of the return statement are all expressions.

Operators

Most expressions are modeled as operators:

Category Operator Syntax Function
Conversion as x as T Converts the value x to the type T.
Logical and x and y A short-circuiting logical AND: true if both operands are true.
Logical or x or y A short-circuiting logical OR: true if either operand is true.
Logical not not x Logical NOT: true if the operand is false.
Comparison == x == y Equality: true if x is equal to y.
Comparison != x != y Inequality: true if x is not equal to y.
Comparison < x < y Less than: true if x is less than y.
Comparison <= x <= y Less than or equal: true if x is less than or equal to y.
Comparison > x > y Greater than: true if x is greater than to y.
Comparison >= x >= y Greater than or equal: true if x is greater than or equal to y.

Conversions and casts

When an expression appears in a context in which an expression of a specific type is expected, implicit conversions are applied to convert the expression to the target type.

Expressions can also be converted to a specific type using an as expression.

fn Bar(n: i32);
fn Baz(n: i64) {
  // OK, same as Bar(n as i32)
  Bar(n);
}

if expressions

An if expression chooses between two expressions.

fn Run(args: Span(StringView)) {
  var file: StringView = if args.size() > 1 then args[1] else "/dev/stdin";
}

if expressions are analogous to ?: ternary expressions in C and C++.