According to a book I read you can pass variables from one function to another by passing by value/address. When you pass by address it will no longer preserve the variable if it is changed in a function and returned back to the original function (ex: main()
). The very next chapter, the book reviews "returning values". In this chapter it explains the use of return(variable);
but doesn't explain a clear purpose. Is return(variable);
used when multiple variables are passed to a certain function to return only one? Or are there other uses? In other words, what's the difference between return;
and return(variable);
?
Passing by address, exact book example without return(num);
:
#include <stdio.h>
main()
{
int i;
i = 4
printf("Before: %d.\n", i);
half(&i);
printf("After: &d.\n", i);
return (0);
}
half (int *i)
{
*i = *i / 2;
printf("During: %d.\n", *i);
return;
}
Returning Values, exact book example with return(num);
:
#include <stdio.h>
float gradeAve(float test1, float test2, float test3);
main()
{
float grade1, grade2, grade3;
float average;
printf("What was the grade on the first test? ");
scanf(" %f", &grade1);
printf("What was the grade on the second test? ");
scanf(" %f", &grade2);
printf("What was the grade on the third test? ");
scanf(" %f", &grade3);
average = gradeAve(grade1, grade2, grade3);
printf("\nWith those three test scores, the average is %.2f", average);
return 0;
}
float gradeAve(float test1, float test2, float test3)
{
float localAverage;
localAverage = (test1+test2+test3)/3;
return (localAverage);
}
How can both of these return values to original function with or without return(num);
?
return;
without a variable name just returns nothing" which seems so obvious it's still unclear to me what you need help with (again, probably due to the confusion). Are you saying you'd expect a function to return one of its arguments even without you writing a return statement? Or are you wondering what the point of areturn;
statement is when it's not returning a value? Or are you trying to ask something about returning one of the parameters that was passed into the function?return;
in a function, that would be a compile-time error. A procedure hasvoid
return and cannot return a value (also would be compile-time error).return value;
doesn't need()
's. We can add extra()
's to any expression if desired, such as1+2
can be written as((1)+(2))
, so some do that asreturn (value);
even though it is does nothing different fromreturn value;
.