没有返回语句的函数返回值 [英] Function returns value without return statement

查看:48
本文介绍了没有返回语句的函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码有正确的输出?int GGT 没有 return 语句,但代码确实有效?没有设置全局变量.

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: 
");
    scanf("%d", &x1);
    scanf("%d", &x2);
    printf("GGT ist: %d
", 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;
        }
    }
}

推荐答案

至少对于 x86,这个函数的返回值应该在 eax 寄存器中.任何存在的东西都会被调用者认为是返回值.

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.

因为eax是作为返回寄存器使用的,所以常被调用者作为scratch"寄存器使用,因为不需要保存.这意味着它很有可能被用作任何局部变量.因为它们最后是相等的,所以更有可能在 eax 中留下正确的值.

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.

这篇关于没有返回语句的函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆