Reputation: 33
Well, like my title says, i want to pass a variable to a function, which ones value will then be edited in a specific way and saved again in the variable. i don't want to make the function return the computed value, i want sth. like this:
void function(variable_name, double computing_value)
{
variable_name *= computing_value;
}
for example. it'd be more comfortable for me this way. (i want to program levels for a game with it). can i do sth. with pointers to get this? like, passing a pointer to the function, and then referring to the variable the pointer points at?
Upvotes: 1
Views: 56
Reputation: 96800
In C++ you no longer need pointers to modify a parameter. You can use a reference instead:
void function(T &t, T y) { // Where T is the type of your argument.
t *= y;
}
In this case the parameter y
will be copied, but not t
. Since it is passed by reference no copy is needed; you're acting on the object itself.
Upvotes: 1
Reputation: 110658
You want a reference type:
void function(double& variable_name, double computing_value)
{
variable_name *= computing_value;
}
Here I've assumed that variable_name
should be a double
. A reference type allows you to pass an argument to the function without it begin copied. That is, variable_name
will be a reference to the object that was passed in.
Note: do not mistake the &
in the type as the "address of" operator. It's not. They are two different meanings for &
in C++. Here we are using it for a reference type.
Upvotes: 3