Macros and constant expressions

How to define something like to the following C code

#define NUM 10

int a[N];

for (int i=0; i<N; ++i) {
a[i] = i+1;
}

For example, a is on the stack, which is possible because the size is known in compile time.

This is how it could be done:

const N: usize = 10;
let mut a = [0; N];
for (i,x) in a.iter_mut().enumerate() {
    *x = i+1;
}

println!("{:?}", a);
// prints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(playground)

Syntactically closer to your C code would be:

const N: usize = 10;
let mut a = [0; N];
for i in 0..N {
    a[i] = i + 1;
}

println!("{:?}", a);
// prints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(playground)

Edit: Note that both examples create arrays of usize, so an unsigned element type.

2 Likes

If you’re ok with a resizable vector instead of a fixed-length array, you could do something like this:

const N:usize = 10;
let a: Vec<i32> = (1..=N).collect();

Thanx a lot