544 views
1 votes
1 votes
A function need not return a value;a return statement with no expression causes control,but no useful value,to be returned to the caller,as does "falling off the end" of a function by reaching the terminating right brace.And the calling function can ignore a value return by a function.---In reference to this ---

#include<stdio.h>

int power(int m,int n);

main()                                                                  /*OUTPUT:---->

{                                                                                       0 0 0

int i;                                                                                  1 1 1

for(i=0;i<10;i++)                                                               2 2 2

printf("%d %d %d\n",i,power(2,i),power(-3,i));                 3 3 3    

return 0;                                                                           4 4 4

}                                                                                       5 5 5

int power(int base,int n)                                                   6 6 6

{  int i,p;                                                                            7 7 7

p=1;                                                                                  8 8 8

for(i=0;i<n;i++)                                                                 9  9 9     */

p=base*p;                                                                          

return;  /* return statement with no expression*/   

}  

What is the reason of such output,and what the given statements want to say?

1 Answer

1 votes
1 votes

According to the C99 standard, your program will throw two warnings. I got 2 warnings : 1) The main should have non-void return type as you are returning 0 at the end. 2) The function declared with non-void return type but returning void(return without an expression).

But in ANSI C (C89/C90) as referred by the book, "main()" implicitly meant "int main()", so you won't get the first warning. If you compile ignoring all warnings, your program will still compile. 

Regarding the behavior you see, it is an "undefined" behavior (Line from the book - "but no useful value,to be returned to the caller"). The return value you see is whatever "random" value that was present in the return register (eg: EAX on x86).

"Because eax is used as return register, it is often used as "scratch" register by calee, because it does not need to be preserved. This means that it's very possible that it will be used as any of local variables. Because both of them are equal at the end, it's more probable that the correct value will be left in eax."

Source : 

https://stackoverflow.com/questions/4644860/function-returns-value-without-return-statement

https://stackoverflow.com/questions/4260048/c-function-defined-as-int-but-having-no-return-statement-in-the-body-still-compi

Related questions