DEV Community

Jesse Phillips
Jesse Phillips

Posted on • Updated on

Indirect Access (Pointers)

I want to show how languages handle accessing data indirectly. To understand indirect access let's look at what direct access would look like.

I usually show the comparison by writing in other languages, but editors in those languages didn't work well on my phone. I also don't know how to add this to a series with the new dev.to interface.

// dlang 
void main() @safe {
    int i = 7;
    int j = i;

    j = 2;
    assert(i == 7);

    void addOne(int num) @safe pure nothrow {
        num = num + 1;
    }

    addOne(i);
    assert(i == 7);
}
Enter fullscreen mode Exit fullscreen mode

Here we see that each variable operates independently of the other values, my addOne function has no actual effect outside the function. Often this is referred to as pass by value.

Let's contrast this with indirect access.

// dlang 
// we see this option in C++ and C#
void main() @safe {
    int j = 7;

    // take the argument by reference
    void addOne(ref int num) @safe pure nothrow {
        num = num + 1;
    }

    addOne(j);

    assert(j == 8);
}
Enter fullscreen mode Exit fullscreen mode

Here we find that the value passed into the function and modified. Let us take a quick look at another way to do the same thing.

// dlang 
// we see this in C and available in C++
void main() {
    int j = 7;

    // accept a pointer to an int
    void addOne(int* num) @safe pure nothrow {
        *num = *num + 1;
    }

    // take the address of where j is stored 
    addOne(&j);

    assert(j == 8);
}
Enter fullscreen mode Exit fullscreen mode

However there are more ways to do this and has been referred to as pass by reference, and this happens with a class.

// dlang 
// we see this option in C# and Java

public class Num {
    int value;
    @safe:
    pure nothrow
    this(int v) { value = v; } 
} 


void main() @safe {
    Num j = new Num(7);

    // take the argument by reference
    void addOne(Num num) @safe pure nothrow {
        num.value = num.value + 1;
    }

    addOne(j);

    assert(j.value == 8);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)