检查函数的返回值没有return语句 [英] Checking return value of a function without return statement
问题描述
使用下面的例子,请解释为什么有时return语句不需要?函数返回类型,但return语句丢失。同时,程序编译和工作正常。
请帮助我更好地理解这种
5
6字符* handleInput(){
8与fgets(缓冲,1024,标准输入);
9 ** //返回缓冲区** LT; ---- COMMENTED RETURN
10}
11
12无效的主要(){
14字符* PTR = handleInput();
15 INT标志=的atoi(PTR);
16,如果(标志℃下)破;
17的printf(您输入:%S \\ n,PTR);
20}
基本上得到返回的是好运气。你得到了什么恰好是在CPU寄存器时,它回来。如果,例如,返回值将是AX,而的char *
恰好是AX,你运气了。我相信这是一个不确定的操作;即C语言规范不告诉你的应的如此,所以这是留给编译器。我很惊讶,一个现代化的编译器不会至少抛出一个警告你。
Using example below, please explain why sometimes return statement is not needed? Function has a return type, but return statement missing. Meanwhile, program compiles and works fine.
Please help me understand this better
5
6 char* handleInput() {
8 fgets(buffer, 1024, stdin);
9 **// return buffer;** <---- COMMENTED RETURN
10 }
11
12 void main() {
14 char* ptr = handleInput();
15 int flag = atoi(ptr);
16 if (flag < 0) break;
17 printf("You entered: %s\n", ptr);
20 }
Basically what gets returned is dumb luck. You get what happens to be in the CPU register when it comes back. If, for example, the returned value would be in AX, and the char*
happens to be in AX, you lucked out. I believe this is an undefined behavior; i.e. the C language specifications don't tell what you should so, so it is left to the compiler. I'm surprised a modern compiler wouldn't at least throw a warning at you.
这篇关于检查函数的返回值没有return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!