042_pointers4.zig 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // Now let's use pointers to do something we haven't been
  3. // able to do before: pass a value by reference to a function.
  4. //
  5. // Why would we wish to pass a pointer to an integer variable
  6. // rather than the integer value itself? Because then we are
  7. // allowed to *change* the value of the variable!
  8. //
  9. // +-----------------------------------------------+
  10. // | Pass by reference when you want to change the |
  11. // | pointed-to value. Otherwise, pass the value. |
  12. // +-----------------------------------------------+
  13. //
  14. const std = @import("std");
  15. pub fn main() void {
  16. var num: u8 = 1;
  17. var more_nums = [_]u8{ 1, 1, 1, 1 };
  18. // Let's pass the num reference to our function and print it:
  19. makeFive(&num);
  20. std.debug.print("num: {}, ", .{num});
  21. // Now something interesting. Let's pass a reference to a
  22. // specific array value:
  23. makeFive(&more_nums[2]);
  24. // And print the array:
  25. std.debug.print("more_nums: ", .{});
  26. for (more_nums) |n| {
  27. std.debug.print("{} ", .{n});
  28. }
  29. std.debug.print("\n", .{});
  30. }
  31. // This function should take a reference to a u8 value and set it
  32. // to 5.
  33. fn makeFive(x: *u8) void {
  34. ??? = 5; // fix me!
  35. }