Passing read only data to procedures, should I never do it by pointer?

As far as I understand, the odin calling convention will pass things by ref or value depending on which is more efficient. I’ve been using pointers instinctively (because of my time with C) but should I just not bother unless I need to modify the data? Are there any cases where I shouldn’t?

1 Like

So long as you don’t need to modify the data, it is fine to pass it as a value. There is the exception however, when you pass two arguments where one is a pointer, the other is a value, and they both are the same argument at the call site. This can lead to an aliasing bug.

For more information, see: Document pass-by-reference behavior for large arguments by Feoramund · Pull Request #287 · odin-lang/odin-lang.org · GitHub

2 Likes

What are the chances a compiler warning gets added for procedures with this argument pattern without an explicit copy inside?

I can imagine how it could be done by examining call sites with procedures that have pointers and >16-byte value arguments, then comparing if any address overlaps in the set of arguments (because remember that this can still happen even with sub-structure data, not just direct pointer-to-struct and value-of-struct; the arguments need not point to the same value), then firing off a warning if there are any uses of the value-based arguments within a procedure body if a write is detected to any of the aforementioned pointers.

But how you do that in the compiler is far beyond my ken at the moment. I think it could be a useful feature to have.

I was thinking something much easier to implement but slightly less useful:

Don’t even check the size of arguments and just state in the warning that the pattern (pointer + value of same data is passed, and no explicit copy) may lead to aliasing bugs.

Or maybe don’t even worry about explicit copy either, since you could shadow the variable and still fall prey to an aliasing bug quite easily; just check the arguments and make it an optional warning is my humble opinion.