Pass the current state of the function to another function in C / C ++

Is there a way to pass the current state of a function to another function in C / C ++? I mean all parameters and local variables by current state. For instance:

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().
}

The code is in poor condition if there is a need for functions funcB(). But can this be achieved?

This can help if someone starts refactoring a long method with several parameters.

+3
source share
9 answers

Introduce a common structure.

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

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

void funcB(State& s)
{
    //...
}
+7
source

gcc supports a Pascal-like extension for C, namely nested functions like

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

Compile this with -nested-functions:

$ gcc -Wall --nested-functions nested.c -o nested

:

$./nested
main: a = 1, b = 2
foo: a = 1, b = 2

, , gcc , .

+5

, , . .

struct SomeAlgo {
    SomeAlgo()
    : c(0), d(0), e(0) // Initialize common variables
    { }
    void funcA(int a,int b)
    {
        c = 1234; //...
        // ...
        funcB();

    }
    void funcB() // You may put it in the private section.
    {
        // Simply use c,d,e here.
    }
private:
    char c;
    int d,e;
};

SomeAlgo alg;
alg.funcA(3,4);

EDITED: . .

+3

, , .

; , .

struct foo {  int d; int e; char c ; } fooinstance;

void afunc( struct foo fi);
void bfunc( struct foo fi);

void afunc( struct foo fi ) {
  // do stuff with fi
  f1.d += fi.e ;
  fi.c++;
  // call b
  b(fi);
}

struct a b. , .

+2

, , , C , .. , . , .

+1

, - .

, -. ( ) -.

+1

, . , . , , .

+1

- . funcB , , , . , - , funcB.

, , , funcB.

0

, , , : . , , - , .

, ++ ( C ), .

lambdas/closures, C/++, .

: , , ...

-3

Source: https://habr.com/ru/post/1731375/


All Articles