Search code examples
ccode-duplication

Is there a function equivalent that can take in statements as arguments?


I have the following section of code that I need to use about 5 times throughout the whole program, but with different lines of code in place of the comment.

while (loop_day < (day+1)) {
    while (loop_size < (size+1)) {

        //new lines here

        size = size + 1;
    }
    loop_day = loop_day + 1;
}

I could copy and paste this multiple times, but I really would rather not, for aesthetic reasons. I tried searching for "functions that could take in statements as arguments", but found nothing appropriate.

Edit: I want to "embed" various statements into the code.

An example:

while (loop_day < (day+1)) {
    while (loop_size < (size+1)) {

        // code that stores various values into an array

        size = size + 1;
    }
    loop_day = loop_day + 1;
}


while (loop_day < (day+1)) {
    while (loop_size < (size+1)) {

        // code that reads values stored in that array

        size = size + 1;
    }
    loop_day = loop_day + 1;
}

But I want something like this:

custom_loop {
// code that stores various values into an array
}

custom_loop {
// code that reads values stored in that array
}

Solution

  • You can think of callback functions. For example,

    typedef void (*t_func)(int, int);
    
    void doLoopOverDaysAndSize(t_func callback)
    {
        while (loop_day < (day+1)) {
            while (loop_size < (size+1)) {
                callback(loop_day, loop_size)
                size = size + 1;
            }
            loop_day = loop_day + 1;
        }
     }
    

    Then you can pass some function like this

    void myDaySizeHandler(int day, int size)
    {
        // do something
    }