Trying to convert a program from C to Zig:

I am attempting to convert a C program into Zig, but I keep getting an error saying:

fathoms.zig:3:19: error: unable to evaluate comptime expression
var feet: u32 = 6 * fathoms;
fathoms.zig:3:21: note: operation is runtime due to this operand
var feet: u32  = 6 * fathoms;
referenced by:
    main: fathoms.zig:7:65
    callMain: /home/jf/Installations/Ziglang/zig_lang/lib/std/start.zig:585:32
    initEventLoopAndCallMain: /home/jf/Installations/Ziglang/zig_lang/lib/std/start.zig:519:34
    callMainWithArgs: /home/jf/Installations/Ziglang/zig_lang/lib/std/start.zig:469:12
    posixCallMainAndExit: /home/jf/Installations/Ziglang/zig_lang/lib/std/start.zig:425:39
    _start: /home/jf/Installations/Ziglang/zig_lang/lib/std/start.zig:338:40

It is the translation from the C statement: feet = 6 * fathoms;

The error message didn’t write correctly in what I am guessing is a preview of this post.

Here is the code snippet:

const std = @import("std");
var fathoms: u32 = 2;
var feet: u32 = 6 * fathoms;

pub fn main() !void {
    const stdout =;
    try stdout.print("There are {d} feet in {d} fathoms!\n", .{ feet, fathoms });
    //    try stdout.print("Yes, I said {d} feet!\n", .{6 * fathoms});

Thanks to anyone who can help!

Both feet and fathoms are global runtime variables. To assign an initial value to a global, the expression on the right-hand side must be a compile-time expression. But fathoms is a runtime variable, so you cannot use it in the initialization of another global.

If you make fathoms a const instead of a var, your program will compile.

Alternatively, if you need its value to change at runtime, you can leave it uninitialized (set it to undefined) in the declaration, then assign it a value inside a function, e.g. main().


Thank you for the explanation hryx, I will try both of those suggestions.

I edited the post to put the error and code in blocks. You can do so by starting and ending them with triple backticks ```


I implemented your suggestions and they both worked. Thanks again!

Ah okay I see. Thanks for the tip dude!

I like your Youtube channel. I haven’t watched all the Zig in Depth guides yet. Just Numeric Operations. I’ve subscribed!

1 Like