#How to break/return from `comptime {}` block?

1 messages · Page 1 of 1 (latest)

south shard
#

I've seen on a forum a trick that if you want a function to be 100% comptime inside, without forcing users to put comptime in front of it, you can do:

const std = @import("std");

fn comptimeFn(comptime a: usize, comptime b: usize) usize {
    return comptime {
        // logic
    };

}

pub fn main() !void {
    var x = comptimeFn(1, 3);
    x += 1;
    std.log.debug("{d}", .{x});
}

However, the comptime block doesn't allow to return from it. What kind of logic can be inside then? (break doesn't work in it, just in case)

strong vector
#
pub fn comptimeFn(comptime a: usize, comptime b: usize) usize {
  const out = comptime blk: {
    break :blk a + b;
  };
  return out;
}
#

any logic that can be run at comptime (pretty much anything but syscalls and heap allocation)