简体   繁体   English

函数指针调用的函数的意外返回值

[英]Unexpected return value of a function called by a function pointer

The return value of the function "fun" is unexpected 函数“fun”的返回值是意外的

I'm learning C by writing a high order function "funfun" to return a function "fun" 我正在通过编写高阶函数“funfun”来学习C来返回一个函数“fun”

#include<stdio.h>
void* funfun(const int k) {
    int fun(const int c) {
            //int sum = k + c;
            printf("k = %d, c = %d, sum = %d\n", k, c, k + c);
            return k + c;
    }
    return fun;
}

int main() {
    int (*ptr)(int) = funfun(3);
    printf("%d\n", ptr(2));
    return 0;
}

Commenting out "int sum = k + c;", the display is unexpected: 注释掉“int sum = k + c;”,显示是意外的:

k = 3, c = 2, sum = 5
134513986

Keeping that line, the display is expected: 保持该行,显示预期:

k = 3, c = 2, sum = 5
5

The code is compiled and executed with: 代码编译和执行:

gcc a.c -o a && ./a

gcc -v shows: gcc -v显示:

gcc version 4.1.2 20080704 (Red Hat 4.1.2-50)

You are using a GCC extension called Nested Functions . 您正在使用名为嵌套函数的GCC扩展。

In that documentation, you can discover that what you are doing is not allowed: 在该文档中,您可以发现您正在做的事情是不允许的:

But this technique works only so long as the containing function (hack, in this example) does not exit. 但是只要包含函数(在本例中为hack)不退出,这种技术才有效。

The "containing function" is funfun in your case. 在你的情况下,“包含功能”是funfun

If you try to call the nested function through its address after the containing function exits, all hell breaks loose . 如果你尝试在包含函数退出后通过其地址调用嵌套函数,那么所有的地狱都会破裂

C does not really have higher-order functions (with closures etc.). C实际上没有高阶函数(带闭包等)。 This extension to C doesn't really provide those either. 对C的这种扩展并没有真正提供这些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM