2.6 Functions and Control Flow

2.6.1 Function Declaration

In Rust:

fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    let result = add(5, 3);
    println!("The sum is: {}", result);
}
  • Functions start with fn.
  • Parameters include type annotations.
  • The return type is specified with ->.

2.6.2 Comparison with C

int add(int a, int b) {
    return a + b;
}

int main() {
    int result = add(5, 3);
    printf("The sum is: %d\n", result);
    return 0;
}

2.6.3 Control Structures

If Statements

Rust:

fn main() {
    let x = 5;
    if x < 10 {
        println!("Less than 10");
    } else {
        println!("10 or more");
    }
}
  • Conditions must be bool.
  • No parentheses required around the condition.

C:

int x = 5;
if (x < 10) {
    printf("Less than 10\n");
} else {
    printf("10 or more\n");
}
  • Conditions can be any non-zero value (not necessarily bool).
  • Parentheses are required.

Loops

while Loop

Rust:

fn main() {
    let mut x = 0;
    while x < 5 {
        println!("x is: {}", x);
        x += 1;
    }
}

C:

int x = 0;
while (x < 5) {
    printf("x is: %d\n", x);
    x += 1;
}
for Loop

Rust's for loop iterates over iterators:

fn main() {
    for i in 0..10 {
        println!("{}", i);
    }
}
  • 0..10 is a range from 0 to 9.
  • No classic C-style for loop.

C:

for (int i = 0; i < 10; i++) {
    printf("%d\n", i);
}
loop

Rust provides the loop keyword for infinite loops:

fn main() {
    let mut count = 0;
    loop {
        println!("Count is: {}", count);
        count += 1;
        if count == 5 {
            break;
        }
    }
}

Assignments in Conditions

Rust does not allow assignments in conditions:

fn main() {
    let mut x = 5;
    // if x = 10 { } // Error: expected `bool`, found `()`
}

You must use comparison operators:

fn main() {
    let x = 5;
    if x == 10 {
        println!("x is 10");
    } else {
        println!("x is not 10");
    }
}

In C, assignments in conditions are allowed (but can be error-prone):

int x = 5;
if (x = 10) {
    // x is assigned 10, and the condition evaluates to true (non-zero)
    printf("x is assigned to 10 and condition is true\n");
}