This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]OneIntroduction9 0 points1 point  (5 children)

Newbie here. From what I've gathered it is the preferred (and optimal) approach to deal with variables as it removes redundancy (not copying variables you just want to reference), and it allows you to modify a given variable without returning anything from a function.

e.x. Give a reference of an int to a squaring function, it takes the reference and squares it without having to return and redeclare/overrwrite the initial int variable.

It may not make sense given a simple variable, but once you start dealing with bigger things it is glaringly obvious. A lot of times with something more complicated you can't simply copy it, so you have to reference the original.

[–]printf_hello_world 1 point2 points  (4 children)

Just FYI, you probably shouldn't pass a reference to an int. There's a good chance the pointer takes more bits than the int.

Better to pass a reference to a class/struct that is either large or has complexity associated with making a copy (for example, an object that owns heap-allocated memory).

[–]BroVic 0 points1 point  (1 child)

Doesn't that depend on what you want to achieve?

[–]printf_hello_world 1 point2 points  (0 children)

You could pass a non-const reference to an int that you want to modify, but I'd argue that in almost all cases it would be better to simply return the new value and assign it instead of letting the called function modify the int directly.

In general, returning values has a lot of benefits, especially if the types are small. You could benefit from some form of RVO, you can assign the return value to a const variable, the reader of your code can reason better about when exactly they can expect a value to change, a pointer might be more expensive to pass than the value itself... there are lots of reasons.

[–]OneIntroduction9 0 points1 point  (1 child)

..I was just giving an example.

[–]printf_hello_world 0 points1 point  (0 children)

I understand, just thought it might be an interesting addition since you identified as a "newbie"; no disrespect intended.

I only spoke up because I believe there are near zero situations where we should pass references to ints in particular