Functions

test_functions.zig

  1. const std = @import("std");
  2. const builtin = @import("builtin");
  3. const native_arch = builtin.cpu.arch;
  4. const expect = std.testing.expect;
  5. // Functions are declared like this
  6. fn add(a: i8, b: i8) i8 {
  7. if (a == 0) {
  8. return b;
  9. }
  10. return a + b;
  11. }
  12. // The export specifier makes a function externally visible in the generated
  13. // object file, and makes it use the C ABI.
  14. export fn sub(a: i8, b: i8) i8 { return a - b; }
  15. // The extern specifier is used to declare a function that will be resolved
  16. // at link time, when linking statically, or at runtime, when linking
  17. // dynamically. The quoted identifier after the extern keyword specifies
  18. // the library that has the function. (e.g. "c" -> libc.so)
  19. // The callconv specifier changes the calling convention of the function.
  20. const WINAPI: std.builtin.CallingConvention = if (native_arch == .x86) .Stdcall else .C;
  21. extern "kernel32" fn ExitProcess(exit_code: u32) callconv(WINAPI) noreturn;
  22. extern "c" fn atan2(a: f64, b: f64) f64;
  23. // The @setCold builtin tells the optimizer that a function is rarely called.
  24. fn abort() noreturn {
  25. @setCold(true);
  26. while (true) {}
  27. }
  28. // The naked calling convention makes a function not have any function prologue or epilogue.
  29. // This can be useful when integrating with assembly.
  30. fn _start() callconv(.Naked) noreturn {
  31. abort();
  32. }
  33. // The inline calling convention forces a function to be inlined at all call sites.
  34. // If the function cannot be inlined, it is a compile-time error.
  35. fn shiftLeftOne(a: u32) callconv(.Inline) u32 {
  36. return a << 1;
  37. }
  38. // The pub specifier allows the function to be visible when importing.
  39. // Another file can use @import and call sub2
  40. pub fn sub2(a: i8, b: i8) i8 { return a - b; }
  41. // Function pointers are prefixed with `*const `.
  42. const Call2Op = *const fn (a: i8, b: i8) i8;
  43. fn doOp(fnCall: Call2Op, op1: i8, op2: i8) i8 {
  44. return fnCall(op1, op2);
  45. }
  46. test "function" {
  47. try expect(doOp(add, 5, 6) == 11);
  48. try expect(doOp(sub2, 5, 6) == -1);
  49. }

Shell

  1. $ zig test test_functions.zig
  2. 1/1 test_functions.test.function... OK
  3. All 1 tests passed.

There is a difference between a function body and a function pointer. Function bodies are comptime-only types while function Pointers may be runtime-known.

Pass-by-value Parameters

Primitive types such as Integers and Floats passed as parameters are copied, and then the copy is available in the function body. This is called “passing by value”. Copying a primitive type is essentially free and typically involves nothing more than setting a register.

Structs, unions, and arrays can sometimes be more efficiently passed as a reference, since a copy could be arbitrarily expensive depending on the size. When these types are passed as parameters, Zig may choose to copy and pass by value, or pass by reference, whichever way Zig decides will be faster. This is made possible, in part, by the fact that parameters are immutable.

test_pass_by_reference_or_value.zig

  1. const Point = struct {
  2. x: i32,
  3. y: i32,
  4. };
  5. fn foo(point: Point) i32 {
  6. // Here, `point` could be a reference, or a copy. The function body
  7. // can ignore the difference and treat it as a value. Be very careful
  8. // taking the address of the parameter - it should be treated as if
  9. // the address will become invalid when the function returns.
  10. return point.x + point.y;
  11. }
  12. const expect = @import("std").testing.expect;
  13. test "pass struct to function" {
  14. try expect(foo(Point{ .x = 1, .y = 2 }) == 3);
  15. }

Shell

  1. $ zig test test_pass_by_reference_or_value.zig
  2. 1/1 test_pass_by_reference_or_value.test.pass struct to function... OK
  3. All 1 tests passed.

For extern functions, Zig follows the C ABI for passing structs and unions by value.

Function Parameter Type Inference

Function parameters can be declared with anytype in place of the type. In this case the parameter types will be inferred when the function is called. Use @TypeOf and @typeInfo to get information about the inferred type.

test_fn_type_inference.zig

  1. const expect = @import("std").testing.expect;
  2. fn addFortyTwo(x: anytype) @TypeOf(x) {
  3. return x + 42;
  4. }
  5. test "fn type inference" {
  6. try expect(addFortyTwo(1) == 43);
  7. try expect(@TypeOf(addFortyTwo(1)) == comptime_int);
  8. const y: i64 = 2;
  9. try expect(addFortyTwo(y) == 44);
  10. try expect(@TypeOf(addFortyTwo(y)) == i64);
  11. }

Shell

  1. $ zig test test_fn_type_inference.zig
  2. 1/1 test_fn_type_inference.test.fn type inference... OK
  3. All 1 tests passed.

inline fn

Adding the inline keyword to a function definition makes that function become semantically inlined at the callsite. This is not a hint to be possibly observed by optimization passes, but has implications on the types and values involved in the function call.

Unlike normal function calls, arguments at an inline function callsite which are compile-time known are treated as Compile Time Parameters. This can potentially propagate all the way to the return value:

inline_call.zig

  1. test "inline function call" {
  2. if (foo(1200, 34) != 1234) {
  3. @compileError("bad");
  4. }
  5. }
  6. inline fn foo(a: i32, b: i32) i32 {
  7. return a + b;
  8. }

Shell

  1. $ zig test inline_call.zig
  2. 1/1 inline_call.test.inline function call... OK
  3. All 1 tests passed.

If inline is removed, the test fails with the compile error instead of passing.

It is generally better to let the compiler decide when to inline a function, except for these scenarios:

  • To change how many stack frames are in the call stack, for debugging purposes.
  • To force comptime-ness of the arguments to propagate to the return value of the function, as in the above example.
  • Real world performance measurements demand it.

Note that inline actually restricts what the compiler is allowed to do. This can harm binary size, compilation speed, and even runtime performance.

Function Reflection

test_fn_reflection.zig

  1. const std = @import("std");
  2. const math = std.math;
  3. const testing = std.testing;
  4. test "fn reflection" {
  5. try testing.expect(@typeInfo(@TypeOf(testing.expect)).Fn.params[0].type.? == bool);
  6. try testing.expect(@typeInfo(@TypeOf(testing.tmpDir)).Fn.return_type.? == testing.TmpDir);
  7. try testing.expect(@typeInfo(@TypeOf(math.Log2Int)).Fn.is_generic);
  8. }

Shell

  1. $ zig test test_fn_reflection.zig
  2. 1/1 test_fn_reflection.test.fn reflection... OK
  3. All 1 tests passed.