I’m trying to distinguish what is const
-ness and how it is related to: values (memory), pointers, variables, and types. It feels like these things have their own life.
I’ve already looked at:
- Pointers and constness in Zig (and why it is confusing to a C programmer) - Zig NEWS
- https://www.youtube.com/watch?v=VgjRyaRTH6E
And it feels like I’m just getting more confused
For example:
const std = @import("std");
const assert = std.debug.assert;
const print = std.debug.print;
test "const-ness" {
const foo: u8 = 1;
var bar: u8 = 1;
assert(@TypeOf(foo) == @TypeOf(bar)); // u8 == u8
const foo1 = &[_]u8{42};
var bar1 = &[_]u8{42};
assert(@TypeOf(foo1) == @TypeOf(bar1)); // *const [1]u8 == *const [1]u8
}
$ zig test file.zig
All 1 tests passed.
Shouldn’t the test have failed? I expected foo
to show up its const-ness somewhere (ie. in its type). Also, I didn’t understand why &[_]u8{...}
translates into a const pointer, ie. *const [1]u8
. I’d greatly appreciate any clarification, or perhaps information on how I can inspect const-ness during compile or runtime.
As for now, my understanding boils down to the following:
- In types, you can’t const values (eg. structs), only pointers. So you can’t write:
const foo: const u8 = 42;
- The const-ness of values can be expressed only through the
const
qualifier of a variable, eg:const name = ...
- “Const pointer” means a pointer to immutable space of memory.
- Pointer itself does not carry any const-ness in its type.
- Instead, the const-ness of a pointer can only be expressed by applying the ‘const’ qualifier to a variable that contains it.