Operators

Operators in Carbon are symbols that perform operations on operands (values or variables). They are essential for building expressions and controlling the flow of programs.

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /  
  • Modulus: % (returns the remainder of division)  

Comparison Operators

Comparison operators are used to compare values and return a boolean result (true or false):

  • Equal to: ==  
  • Not equal to: !=
  • Greater than: >
  • Less than: <
  • Greater than or equal to: >=
  • Less than or equal to: <=

Logical Operators

Logical operators are used to combine boolean expressions:  

  • Logical AND: && (returns true if both operands are true)
  • Logical OR: || (returns true if at least one operand is true)
  • Logical NOT: ! (reverses the value of its operand)  

Assignment Operators

Assignment operators are used to assign values to variables:

  • Simple assignment: =
  • Compound assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

Bitwise Operators

Bitwise operators are used to perform operations on individual bits of integers:

  • Bitwise AND: &
  • Bitwise OR: |
  • Bitwise XOR: ^
  • Bitwise NOT: ~
  • Left shift: <<
  • Right shift: >>

Precedence and Associativity

The order in which operators are evaluated is determined by their precedence and associativity. Operators with higher precedence are evaluated first. If operators have the same precedence, their associativity determines the evaluation order (left-to-right or right-to-left).  

Examples

Code snippet

var x: int = 10;
var y: int = 5;

var sum: int = x + y;
var difference: int = x - y;
var product: int = x * y;
var quotient: int = x / y;
var remainder: int = x % y;

var isGreater: bool = x > y;
var isEqual: bool = x == y;

var result1: bool = x > 5 && y < 10;
var result2: bool = x > 5 || y < 10;
var result3: bool = !isGreater;

x += 2; // Equivalent to x = x + 2;

By understanding operators and their usage, you can effectively build complex expressions and control the behavior of your Carbon programs.

Variables, Data Types, and Output
Tuples

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?