# Call by value / call by reference

**URL:** <https://ziggit.dev/t/call-by-value-call-by-reference/483>\
**Category:** Help\
**Created:** [December 2, 2022, 7:36pm UTC](https://ziggit.dev/t/call-by-value-call-by-reference/483 "2022-12-02T19:36:25Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![tuxic](https://ziggit.dev/letter_avatar_proxy/v4/letter/t/90db22/32.png) [@tuxic](https://ziggit.dev/u/tuxic)\
**Post date:** [December 2, 2022, 7:36pm UTC](https://ziggit.dev/t/call-by-value-call-by-reference/483/1 "2022-12-02T19:36:25Z")

</div>

I want to pass a struct to a function with “call by reference”?  
Is this done via good old fashioned pointers like in C or more  
advanced with ‘&’-references like in C++? Or anything totally  
different?  
I searched “call by reference zig” the internet…but found  
nothing…

Cheers!  
tuxic

---

<div class="post-metadata">

**Author:** ![kristoff](https://ziggit.dev/user_avatar/ziggit.dev/kristoff/32/9_2.png) [@kristoff](https://ziggit.dev/u/kristoff)\
**Post date:** [December 2, 2022, 7:55pm UTC](https://ziggit.dev/t/call-by-value-call-by-reference/483/2 "2022-12-02T19:55:34Z")

</div>

just normal pointers

```zig
const MyStruct = struct {};

fn foo(arg: *MyStruct) void {
   // ...
}

```

Do `*const MyStruct` if you don’t want it to be mutable.

---

<div class="post-metadata">

**Author:** ![dee0xeed](https://ziggit.dev/letter_avatar_proxy/v4/letter/d/3ab097/32.png) [@dee0xeed](https://ziggit.dev/u/dee0xeed)\
**Post date:** [December 6, 2022, 7:18am UTC](https://ziggit.dev/t/call-by-value-call-by-reference/483/3 "2022-12-06T07:18:07Z")

</div>

```zig
const std = @import("std");

const Object = struct {
    a: i32,
    b: i32,
};

fn show(o: *Object) void {
    std.debug.print("{}\n", .{o.a + o.b});
}

pub fn main() !void {
    var objectOnStack = Object {
        .a = 1,
        .b = 2,
    };
    show(&objectOnStack);

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer std.debug.print("leakage?.. {}\n", .{gpa.deinit()});
    const allocator = gpa.allocator();

    var objectOnHeap = try allocator.create(Object);
    objectOnHeap.a = 3;
    objectOnHeap.b = 4;
    show(objectOnHeap);
    allocator.destroy(objectOnHeap);
}

```

```zig
$ ./byref 
3
7
leakage?.. false

```

---

<div class="post-metadata">

**Author:** ![jmc](https://ziggit.dev/user_avatar/ziggit.dev/jmc/32/38_2.png) [@jmc](https://ziggit.dev/u/jmc)\
**Post date:** [December 8, 2022, 12:16am UTC](https://ziggit.dev/t/call-by-value-call-by-reference/483/4 "2022-12-08T00:16:28Z")

</div>

Also note that in most cases you might not need to do _anything_ if your worry is just avoiding copies of the function argument:

From [Documentation - The Zig Programming Language](https://ziglang.org/documentation/0.10.0/#Pass-by-value-Parameters:)

> Primitive types such as [Integers](https://ziglang.org/documentation/0.10.0/#Integers) and [Floats](https://ziglang.org/documentation/0.10.0/#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.

If you need _mutability_, then a pointer is the way to go as the other posters have shown above.

---

<div class="post-metadata">

**Author:** ![matklad](https://ziggit.dev/user_avatar/ziggit.dev/matklad/32/2462_2.png) [@matklad](https://ziggit.dev/u/matklad)\
**Post date:** [December 12, 2022, 3:25pm UTC](https://ziggit.dev/t/call-by-value-call-by-reference/483/5 "2022-12-12T15:25:38Z")

</div>

I think the rough intention is:

- if you’d use `const& T` in C++ (or `&T` in Rust), just use `T`. “by value” parameters are implicitly by reference.
- if you’d use `&T`, `&mut T`, pass `*T`

Though, this intention is not fully realized yet: there are some bugs in language semantics/compiler which cause strange results in the presence of aliasing:

> <https://github.com/ziglang/zig/issues/5973>
>
> Zig 0.6.0 (not master). This is related to, actually maybe a subset of, https://…github.com/ziglang/zig/issues/4021 / https://github.com/ziglang/zig/issues/3696 (this issue doesn't involve result copy elision).
> 
> I understand that this was intended to be a feature of zig: args passed as values "may" be silently translated to pass-by-reference by the compiler. I think the intent was to stop the user from passing const pointers as an "optimization". But it's also a footgun, sort of like https://github.com/ziglang/zig/issues/2915. The problem occurs when you have another non-const pointer aliasing the same memory as the argument value.
> 
> \`\`\`zig
> const std = @import("std");
> 
> const Thing = struct {
> value: u32,
> };
> 
> const State = struct {
> thing: Thing,
> };
> 
> fn inner(state: \*State, thing: Thing) void {
> std.debug.warn("before: {}\\n", .{thing.value}); // prints 10
> 
> state.thing.value = 0;
> 
> std.debug.warn("after: {}\\n", .{thing.value}); // prints 0
> }
> 
> pub fn main() void {
> var state: State = .{
> .thing = .{ .value = 10 },
> };
> inner(&state, state.thing);
> }
> \`\`\`
> 
> The behavior here depends on the compiler implementation. It seems that right now, if \`thing\` is a struct value, it's passed by reference. But if it's a bare \`u32\`, it's passed by value. I don't know if it will always be this simple (I assume there are plans to pass "small" structs by value.)
> 
> The workaround for this situation is to make an explicit copy using a redundant-seeming optimization, probably accompanied by a comment explaining what's going on. Or else to restructure the code at a higher level, but then this footgun will still be lurking in the shadows.
> 
> I think that any optimistic "assume no aliases" optimization ought to be opt-in rather than opt-out. That would mean, either go back to the C way of things, or add a new syntax (some symbol that means "compiler can choose between value and const pointer"). Either way, a plain argument should always be passed by value. What do others think?
