Question:
How do you use void functions and pass by reference/values with c++?
anonymous
2011-03-07 21:18:16 UTC
I'm new to c++ programing and am havign a hard time figuring out how to use void functions and pass by references/values.

Please help.
Three answers:
anonymous
2011-03-08 21:34:18 UTC
What are you looking for help with? When to use them? How to use them? To declare a void function, you just set the return type as void



void functionName();



to call, you just use the name



functionName();



Passing by reference versus by value....



When you pass by reference you are passing direct access to that argument, as opposed to by value which passes a copy of the argument. For example...



This function passes the argument x by reference, and you can directly manipulate the variable



void passByRef(int& x)

{

x = x + 2;

}



Now, when you call that function with a variable, it will actually change that variable by adding two...



int num = 6;

passByRef(num);



num now equals 8



To pass by value, you pass a copy of the argument to the function, and so the function can't directly change the value of the variable



void passByVal(int x)

{

x = x + 2;

}



int num = 6;

passByVal(num);



num still equals 6!



When should you pass by value or by reference? Well, one reason you may HAVE to pass by reference is if you want to change multiple variables in one function call. For example...



passByRefTwo(int& x, int& y)

{

x = x + 2;

y = y + 3;

}



You may want to pass by value if you want to make sure you don't change the original value of a variable. Hope this helps, and if you clarify what answers you're looking for exactly we may be able to answer more appropriately.
?
2016-11-12 02:35:39 UTC
//double calcWeightLoss(double, double); - unique fact void calcWeightLoss(double, double, double*); -- new fact . . . // weight reduction = calcWeightLoss(weightBefore, weightAfter); //weight reduction = weightBefore - weightAfter; calcWeightLoss(weightBefore, weightAfter, &weight reduction); // instead of above 2 traces //For the function header void calcWeightLoss(double weightBefore, double weightAfter, double* weight reduction); in this way u are passing weight alleviation via connection with the tactic and then getting the cost of it. you do no longer ought to return any element now... Passing via reference is finished via the seen policies..
anonymous
2016-09-15 06:10:06 UTC
I frequently spend my half an hour to read this blog's posts daily along with a mug of coffee.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...