将函数的当前状态传递给C/C++中的另一个函数

san*_*and 3 c c++ function calling-convention

有没有办法将函数的当前状态传递给C/C++中的另一个函数?我的意思是当前状态的所有参数和局部变量.例如:

void funcA (int a, int b)
{
    char c;
    int d, e;
    // Do something with the variables.
    // ...
    funcB();
    // Do something more.
}

void funcB()
{
    // funcB() should be able to access variables a,b,c,d & e
    // and any change in these variables reflect into funcA().
}
Run Code Online (Sandbox Code Playgroud)

如果需要funcB()某种功能,代码就会很糟糕.但它可以实现吗?

如果有人开始使用多个参数重新计算长方法,这可能会有所帮助.

Not*_*ist 7

介绍一个通用的结构.

struct State {
    char c;
    int d,e;
};

void funcA(int a, int b){
    State s;
    s.d = 1234; // ...
    // ...
    funcB(s);
}

void funcB(State& s)
{
    //...
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*l R 5

gcc支持类似于Pascal的扩展,即嵌套函数,例如

#include <stdio.h>

int main(void)
{
    int a = 1, b = 2;

    void foo(void)
    {
        printf("%s: a = %d, b = %d\n", __FUNCTION__, a, b);
    }

    printf("%s: a = %d, b = %d\n", __FUNCTION__, a, b);

    foo();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

用--nested-functions编译它:

$ gcc -Wall --nested-functions nested.c -o nested
Run Code Online (Sandbox Code Playgroud)

然后运行它:

$./nested
main: a = 1, b = 2
foo: a = 1, b = 2
Run Code Online (Sandbox Code Playgroud)

当然这是不可移植的,但是如果你只使用gcc并且你有太多遗留代码要重写,那么这可能是一个很好的解决方案.