top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What a return statement returns ?

+5 votes
320 views
$ cat return.c
#include <stdio.h>
#include <stdlib.h>
int fun1(int i)
{
        return ;
}
int main()
{
        int i = 0;
        for (i = 0; i<5; i++)
        {
                printf("\t%d\n",fun1(i));
        }
        return 0;
}
$ ./a.out
        0
        1
        2
        3
        4
$
posted Dec 21, 2013 by Vikas Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

–1 vote

Your program has undefined behaviour. It fails to return values from fun1. Anything could happen.

The fact that it compiles at all implies that your compiler adheres to an older standard.

For instance C89 says:

If a return statement without an expression is executed, and the value of the function call is used by the caller, the behavior is undefined. Reaching the } that terminates a function is equivalent to executing a return statement without an expression.

On the other hand C99 says:

A return statement without an expression shall only appear in a function whose return type is void.

So, if your compiler adheres strictly to C99 or later then your code is invalid.

It's a little pointless reasoning about why the program behaves as it does, since its behaviour is undefined. Perhaps the ABI for this compiler happens to expect the return value to be placed in a register which also contains the value of the caller's loop variable i when fun1 was called. In any case, your program could output anything at all.

Since fun1 has a return type that it not void, you should use the form of the return statement that has an expression. For instance:

int fun1(int i)
{
return i;
}

answer Dec 21, 2013 by Atul Khanduri
Similar Questions
0 votes

Used the sizeof of function, which gives 1; why?
I want to know the size of the entire function. How to achive it?

#include <stdio.h>
void (*p)(int); 
void test_func(int data)
{
  printf("%d\n",data);
}

main(void)
{
    p = test_func;
    (*p)(4);
    printf("%d",sizeof(test_func));
}
+2 votes

If I correct , by default main () function has integer return type.
I want to know what happens in the system internally when its return type gets changed from integer to void ?

+3 votes
#include <stdio.h>
int main()
{
    char vowels[5]={'a','e','i','o','u'};
    int x;

    printf("Vowel Letters");
    for(x=0;x<=5;x++)
    {
         printf("\n %C",vowels[x]);
    }
}

Output

Vowel Letters
a
e
i
o
u
♣
Process exited after 0.1132 seconds with return value 3

What is the meaning of return value 3

...