Confusion about runtime modification of variable that is not comptime-known

Hi everyone, I recently got help to resolve a confusion I had about an error: unable to resolve comptime value. Stepping away from that discussion, I had this tangential thought that is now confusing me.

Suppose we define a variable var count: u8 = 1 – this is not comptime-known by virtue of not being const or comptime. Therefore, why is it necessary to give count an explicit fixed-size number type to modify the variable at runtime? Is the number type (u8 in this example) ingested at runtime in some manner? is it processed by the compiler, despite count not technically being comptime-known, then the information of the number type communicated to the runtime?

I am new to compiled languages and Zig, so I really appreciate discussion surrounding these concepts for my learning.

Thank you :slight_smile:

The literal numbers in your source e.g. 1 have the type of comptime_int, which is a type that can only exist at comptime, before it can be put in a var you need to convert it to a type that can exist at runtime such as u8.

comptime_int will implicitly convert to a runtime integer type if its value fits, if the value does not fit in the runtime type you get a compile error, which is possible because comptime_int values are comptime known.

Unlike runtime integers, comptime_int can hold any value, even values that don’t fit in any runtime integer zig supports!

The situation is the same for float literal values 1.0 have a type of comptime_float, however they cannot have any value/precision as they are just an f128 in disguise.
Since their values are also required to be comptime known, they can implicitly convert to runtime (and comptime) integers if they are whole (and fit).

types are always comptime known as types can only exist at comptime; at runtime it is just raw bits and bytes, and the code that interacts with it.

Zig has no runtime, at least not in the sense that you are fimiliar with. What you could call its runtime is a minimal set of functions needed to implement some intrinsic things like copying a region of memory to another, or an operation not all cpus support

These things are typical for low level compiled languages.

5 Likes

Thank you for your detailed response! This answered my question and more :slight_smile: