Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returns value without return statement

Tags:

c

return-value

Why does following code has a correct output? int GGT has no return statement, but the code does work anyway? There are no global variables set.

#include <stdio.h> #include <stdlib.h>  int GGT(int, int);  void main() {     int x1, x2;     printf("Bitte geben Sie zwei Zahlen ein: \n");     scanf("%d", &x1);     scanf("%d", &x2);     printf("GGT ist: %d\n", GGT(x1, x2));     system("Pause"); }  int GGT(int x1, int x2) {     while(x1 != x2) {         if(x1 > x2) {             /*return*/ x1 = x1 - x2;         }         else {             /*return*/ x2 = x2 - x1;         }     } } 
like image 705
Pascal Bayer Avatar asked Jan 10 '11 08:01

Pascal Bayer


People also ask

Should a function contains return statement if it does not return a value?

A value-returning function should include a return statement, containing an expression. If an expression is not given on a return statement in a function declared with a non- void return type, the compiler issues a warning message.

How can a function return without value?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

Can you have a function without a return?

Answer. NO, a function does not always have to have an explicit return statement. If the function doesn't need to provide any results to the calling point, then the return is not needed. However, there will be a value of None which is implicitly returned by Python.

What happens if you call a function that has a return value but you don't save the return value in a variable?

nothing, the return value gets ignored.


1 Answers

For x86 at least, the return value of this function should be in eax register. Anything that was there will be considered to be the return value by the caller.

Because eax is used as return register, it is often used as "scratch" register by callee, 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.

like image 183
ruslik Avatar answered Oct 05 '22 22:10

ruslik