0

I have a function (not the main function) wherein I generate arrays of size which is determined from input files, so I can't hardcode it.

I have a massive switch statement where I have about a thousand lines of code repeating the same 50 lines, which loop through and interact with the arrays according to some logic that changes w.r.t. the switch.

The simplest, easiest way that I can think to solve this problem would be to declare a sub-function within the overall function, where the arrays would be accessible by the function.

So,

my_outer_func(){
     int x[5] = {0};

     void my_inner_function(){
         for (int i = 0; i < 5; i++){
             x[i] += 1;             
         } 
     }

     my_inner_function();
}

However, this does not compile. This is something that I would routinely do in F# or another functional language. How would I implement this in C++?

Alternatively, how would I achieve the functionality I am looking for?


If you run into the same problem as me, and you go to lambda functions, here is an example that will do what I have written above:

my_outer_func(){
    auto test = [&x]{
        for (int i = 0; i < 5; i++){
            x[i] += 1;
        }
    };
    test();
}

And with inputs:

my_outer_func(){
    auto test = [&x](int a){
        for (int i = 0; i < 5; i++){
            x[i] += a;
        }
    };

    test(4);
} 
Chris
  • 28,822
  • 27
  • 83
  • 158

0 Answers0