Reference to small types = superfluous?

Started by
5 comments, last by Exellion 20 years, 9 months ago
By passing references to functions instead of a copy of the data we only send a memory address (4 bytes), right? The use of this is very clear when handling large structures but what about when I pass an int or a char? These types are so small that the same amount of data would be sent in either case (reference or not reference). So, to the real question: Is it still better to pass an int as a reference because of the copying that occurs otherwise?
Advertisement
It''s better to pass int by value because then it can be directly accessed. By sending it as a referece, it only sends it''s address, and the value has to be looked up every time you use the reference.. Passing 8 byte structures by value can also be faster than passing them by value, due to the indirect access with references.
> Passing 8 byte structures by value can also be faster than passing them by value

You know what I meant to say..
Aha, cool. Never thought of it that way with 8 byte stuctures and such. Thx!
Depends on what you''re gonna do with the integer. If you pass it to a function that (for example) doubles it, it would be better to pass it with a pointer or referance and alter the memory inside the function instead of first making a copy of the value, double the copy and return it by the return value of the function.

Anyway, there can''t be _too_ much of a speed difference whether you copy the integer or not; just keep it simple as possible is my advice.

-Lord Maz-
-Lord Maz-
That''s the only problem with a reference - so easy to forget it''s actually a pointer in disguise. Though that''s also it''s advantage for ease of use! Persoanlly I prefer pointers to references as it''s closer to the machine code - references are an abstraction sort of wheras pointers have a direct ASM equaivalent. Just my 2c!
You should apply this simple rule :

If you''re passing an object/structure :
- Pass it by const reference if it is a read only argument
- Pass it by reference if it is a read/write argument

If you''re passing a standard type variable :
- Pass it by value if it is a read only argument
- Pass it as a reference if it is a read/write argument

> Is it still better to pass an int as a reference because of the
> copying that occurs otherwise?

If you pass it by reference, you still have to push its address on the stack (as you would with its value).

This topic is closed to new replies.

Advertisement