Given the two code examples which is preferred? In the first the return variable is defined as a local variable. In the second the return variable is passed by the caller. Are you allowed to define a function and return a variable that was passed to it? I’s this simply a preference of one or the other? is there a performance difference?
float compute_diam(float circumference, float pi) {
float rval;
/* Circumference = pi * diameter, so
diameter = circumference / pi */
rval = circumference / pi;
return rval;
}
and
float compute_diam(float circumference, float pi, float rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
rval = circumference / pi;
return rval;
}
Thanks
I think in these two cases the 1st one is better for following reason
1. Due to performance as you are passing variable by value it is once created where ever you declare rval, and once when you pass that rval to function with value of first rval copied to second.
instead if you want to pass variable in this manner pass it by reference as
after completion of the function variable result will hold the value of diameter.