Is the return command in a non-void function necessary?

c, function, return-value

Solution

Is it necessary the return command in a non-void function?

Yes. This is necessary to return a value from a non-`void` function.

Omitting the `return` statement from your function but assigning it to `sum` in `main` will invokes undefined behavior. In this case sometimes you may get the result you expected and sometimes what I expect and sometimes what compiler expects!! Sometimes it may get crashed also. As Pascal Couq mentioned in his comment:

6.9.1 Function definitions:

12: If the `}` that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

Problem

I asked this question before and I understood many things. I suspect that something similar is happening here, so I want to be sure about it. I have this simple program who adds 2 numbers. ``` #include <stdio.h> int addFunc(int, int); int main() { int sum; int num1=1, num2=2; sum = addFunc(num1,num2); //function call printf("\nsum = %d\n\n", sum); return 0; } int addFunc(int a,int b) //function declarator { int add; add = a + b; return add; //return statement of function. } ``` Since this function isn't `void` there is a `return` statement in the function. If I omit the return value, save it and compile it, I don't get any errors from the compiler (nor warnings). And when I run it it gives me a correct result. But how does the program know which value to return, since I don't specify any? Does C return the last calculated variable in the function?

Original source