如果没有明确的“返回",函数将返回什么 [英] What will a function return if there's no explicit 'return'

查看:12
本文介绍了如果没有明确的“返回",函数将返回什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在忘记编写函数的return子句时遇到了这个问题,但是gcc中没有警告或错误.我修复了它,但开始想知道为什么函数会在没有 return 的情况下返回 meaningless 的东西.以下是我尝试过的一些示例:

I bumped into this problem when I forgot to write the return clause of a function, but there was no warning or error in gcc. I fixed it but started wondering why the function would return something meaningless without a return. Here are some examples I tried:

#include "stdio.h"
#include "stdlib.h"

int func1 () {
        int i;
        i = 2;
}

int func2 (int a) {
        int i = a+3;
}

int func3 () {
        int i;
        for (i = 0; i <= 1; i++);
}

int main(void) {
        int a = 0;
        int b = 0;
        int c = 0;
        a = func1();
        printf("a = %d 
", a);
        b = func2(a);
        printf("b = %d 
", b);
        c = func3();
        printf("c = %d 
", c);
}

结果是:

a = 1 
b = 4 
c = 7 

我的问题:

1) 为什么会出现这些结果?这有什么一般规则吗?
2)为什么要保留这个东西而不是报错?它可以在某处以某种方式有用"吗?

1) why these results? Is there any general rule for this?
2) why keep this thing rather than report an error? Can it be somehow 'useful' somewhere?

推荐答案

这是 未定义行为并且将取决于所使用的 调用约定.如果调用者期望寄存器中的结果,那么将使用寄存器中最后的值.

This is undefined behavior and will depend on the calling convention being used. If the caller is expecting the result in a register then whatever value was last in the register will be used.

编辑

C99 标准草案部分6.9.1 函数定义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.

clang 默认会发出警告,gcc 会用 -Wall 发出警告,一般来说你应该启用警告.

clang will warn by default and gcc will warn with -Wall, in general you should enable warnings.

这篇关于如果没有明确的“返回",函数将返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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