067_comptime2.zig 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // Understanding how Zig treats numeric literals is fundamental
  3. // and important, but it isn't exactly exciting.
  4. //
  5. // We're about to get into the cool wizard stuff that makes
  6. // programming computers fun. But first, let's introduce a new and
  7. // vital Zig keyword:
  8. //
  9. // comptime
  10. //
  11. // When you put 'comptime' in front of a variable declaration,
  12. // function parameter, or expression, you're saying, "I want Zig
  13. // to evaluate this at compile time rather than runtime."
  14. //
  15. // We've already seen that Zig implicitly performs certain types
  16. // of evaluations at compile time. (Many compilers do a certain
  17. // amount of this, but Zig is explicit about it.) Therefore,
  18. // these two statements are equivalent and using the 'comptime'
  19. // keyword here is redundant:
  20. //
  21. // const foo1 = 5;
  22. // comptime const foo2 = 5;
  23. //
  24. // But here it makes a difference:
  25. //
  26. // var bar1 = 5; // ERROR!
  27. // comptime var bar2 = 5; // OKAY!
  28. //
  29. // 'bar1' gives us an error because Zig assumes mutable
  30. // identifiers will be used at runtime and trying to use a
  31. // comptime_int of undetermined size at runtime is basically a
  32. // MEMORY CRIME and you are UNDER ARREST.
  33. //
  34. // 'bar2' is okay because we've told Zig that this identifier
  35. // MUST be resolvable at compile time. Now Zig won't yell at us
  36. // for assigning a comptime_int to it without a specific runtime
  37. // size.
  38. //
  39. // The comptime property is also INFECTIOUS. Once you declare
  40. // something to be comptime, Zig will always either:
  41. //
  42. // 1. Be able to resolve that thing at compile time.
  43. // 2. Yell at you.
  44. //
  45. const print = @import("std").debug.print;
  46. pub fn main() void {
  47. //
  48. // In this contrived example, we've decided to allocate some
  49. // arrays using a variable count!
  50. //
  51. // Please make this work. Please?
  52. //
  53. var count = 0;
  54. count += 1;
  55. var a1: [count]u8 = .{'A'} ** count;
  56. count += 1;
  57. var a2: [count]u8 = .{'B'} ** count;
  58. count += 1;
  59. var a3: [count]u8 = .{'C'} ** count;
  60. count += 1;
  61. var a4: [count]u8 = .{'D'} ** count;
  62. print("{s} {s} {s} {s}\n", .{a1, a2, a3, a4});
  63. }