041_pointers3.zig 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //
  2. // The tricky part is that the pointer's mutability (var vs const) refers
  3. // to the ability to change what the pointer POINTS TO, not the ability
  4. // to change the VALUE at that location!
  5. //
  6. // const locked: u8 = 5;
  7. // var unlocked: u8 = 10;
  8. //
  9. // const p1: *const u8 = &locked;
  10. // var p2: *const u8 = &locked;
  11. //
  12. // Both p1 and p2 point to constant values which cannot change. However,
  13. // p2 can be changed to point to something else and p1 cannot!
  14. //
  15. // const p3: *u8 = &unlocked;
  16. // var p4: *u8 = &unlocked;
  17. // const p5: *const u8 = &unlocked;
  18. // var p6: *const u8 = &unlocked;
  19. //
  20. // Here p3 and p4 can both be used to change the value they point to but
  21. // p3 cannot point at anything else.
  22. // What's interesting is that p5 and p6 act like p1 and p2, but point to
  23. // the value at "unlocked". This is what we mean when we say that we can
  24. // make a constant reference to any value!
  25. //
  26. const std = @import("std");
  27. pub fn main() void{
  28. var foo: u8 = 5;
  29. var bar: u8 = 10;
  30. // Please define pointer "p" so that it can point to EITHER foo or
  31. // bar AND change the value it points to!
  32. var p: *u8 = undefined;
  33. p = &foo;
  34. p.* += 1;
  35. p = &bar;
  36. p.* += 1;
  37. std.debug.print("foo={}, bar={}\n", .{ foo, bar });
  38. }