Handmade Hero»Forums»Code
Andras Koczka
5 posts
References in function args when passing structs
Hi Casey,

After last weeks episode discussing pointers vs references in the Q&A, I was thinking about why do not we use references in function arguments? I saw you mentioning this issue of arrows vs dots on the stream several times, also that you do not see a good reason for using references. I think this might be a good use case for that, using references only for this case when passing along structs in function arguments. With that syntax would just get out of the way. So, when we pass structs to functions I think we should do it either via value or by using references - instead of pointers. This way we won’t have to change any code within the function that accessed the members of that struct, also we won’t have to make any change on the call side. So no more rewriting dots to arrows and adding &-s to function calls, we could just freely change the function signature by adding / removing & to that struct argument and that would be the only place that needs to be changed. The only disadvantage I could think of is that someone looking at the function call would not be able to tell if the struct was passed by reference or value, but I think that is only a small problem, and that problem may should be the concern of the function and not the caller anyway.

What do you think?
Mārtiņš Možeiko
2559 posts / 2 projects
References in function args when passing structs
That would work yes, but not in following two cases - to pass NULL for optional pointers, and new values to pointers inside function. And if you need to switch pointers to references or other way around when you decide change pointer argument to be optional or not, it gets messy fast.
popcorn
70 posts
References in function args when passing structs
I would just use classes to accomplish this because it's easier but he doesn't use classes so it's not an option.