after some research, due to not really clear example in chapter 1.7 in "the C Programming language" by K & R, I understood that return
is conventionally present at the end of each function, marking its end;
it seems that by default, the value of return is 0
, which means that the function was performed successfully (which exactly means what?).
what happens if we set the value of return to the variable we call?
for example, if I will write:
return p;
does it mean that the final value of the funcion will be p
?
So for example, if I call this funcion from main()
, or another function, will the value of this function, inside main()
be p
?
Example:
#include <stdio.h>
int power(int m, int n);
/* test power function */
int main(){
int i;
for(i = 0; i < 10; i)
printf("%d - =", i, power(2,i), power(-3,i));
return 0;
}
int power(int base, int n)
{
int i, p;
p=1;
for(i=1;i<=n; i)
p=p*base;
return p;
}
does it mean that when i call power()
in main its value is p
?
CodePudding user response:
The value returned by power
is the value of p
.
Functions don't have a value; functions return a value.
p
is not a value; p
is a variable.
The value returned by power
is the value of p
when return p
is evaluated. So if the value of p
is 8
, the value returned is 8
.
The above program passes the returned value to printf
to print.
it seems that by default, the value of return is
0
Functions don't have a default return value. If the function has a return type other than void
, return
must be used.
main
is the sole exception. return 0
is the default for main
.