函数返回值,而不return语句 [英] Function returns value without return statement

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

问题描述

为什么以下code有一个正确的输出? INT GGT没有return语句,但code不工作呢?有没有设置全局变量。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;INT GGT(INT,INT);无效的主要(){
    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));
    系统(暂停);
}INT GGT(INT X1,X2 INT){
    而(X1!= X2){
        如果(X1> X2){
            / * *回报/ X1 = X1 - X2;
        }
        其他{
            / * *回报/ X2 = X2 - X1;
        }
    }
}


解决方案

对于x86,至少,这个函数的返回值应在 EAX 注册。任何被那里将被认为是由呼叫者的返回值。

由于 eax中被用作返回寄存器,它通常被用作刮由飞翔距离寄存器,因为它并不需要是preserved。这意味着,这是非常可能的,它将被用作任何局部变量。因为他们两人都是在最后平等的,它更可能是正确的值将在 EAX 离开了。

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;
        }
    }
}

解决方案

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 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.

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

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