Control flow
C++:
#include <iostream>
using namespace std;
int main()
{
int x = 1;
if(x > 0)
{
cout << "Positive number" << endl;
}
else if(x < 0)
{
cout << "Negative number" << endl;
}
else
{
cout << "Zero" << endl;
}
for(int i = 0; i < 10; i++)
{
cout << i << "*" << i << "=" << i*i << endl;
}
int t = 10;
while(t < 100)
{
t += t/2;
}
cout << t << endl;
t = 0;
do
{
cout << t << endl;
t += 2;
}while(t <= 10);
int age = 15;
if(age <= 12)
cout << "A child" << endl;
else if(age <= 19)
cout << "A teenage at the age of " << age << endl;
else
cout << "An adult at the age of " << age << endl;
}
Rust :
fn main()
{
let x = 1;
if x > 0
{
println!("Positive number");
}
else if x < 0
{
println!("Negative number");
}
else
{
println!("Zero");
}
for i in 0..10
{
println!("{}*{}={}", i, i, i*i);
}
let mut t = 10;
while t < 100
{
t += t/2;
}
println!("{}", t);
t = 0;
loop
{
println!("{}", t);
t += 2;
if !(t <= 10)
{
break;
}
}
let age = 15;
match age
{
0...12 => println!("A child"),
n @ 13...19 => println!("A teenage at the age of {}", n),
n => println!("An adult at the age of {}", n)
}
}
Most of flow control syntax in C++ and Rust are similar, besides, Rust does not require parentheses in condition clauses. Rust match syntax is more flexible than C++ switch/case syntax (which is not shown in this example).