Search code examples
cstructbinary-treereturn-valueabstract-syntax-tree

Create a tree using struct and for loops in C


I have a question. I'm trying to create a tree. The full code is large so it is difficult for me to enter here. So a summary of it is given below.

struct sample *fn_02(void);
struct sample *fn_03(void);

// Main Function
int main(void) {
    struct sample *tree;

    tree = fn_01();
}

// First Function
struct sample *fn_01(void) {
    for(;;) {
        switch(..) {
            case 1:
                return fn_02();

            case 2:
                return fn_03();
        }
    }
}

// Second Function
struct sample *fn_02(void) {
    struct sample *node;

    return node;
}

// Third Function
struct sample *fn_03(void) {
    struct sample *node;

    return node;
}

I want to create a tree. So I create a structure called struct sample {}; and create a 3 functions for it.

There is an infinity loop in the first ( fn_01() ) function and The values returned by fn_02 and fn_03 should create a tree.

This is the problem I have:

  • The loop in fn_01 should continue to work.
  • But when fn_02 and fn_03 are returned the loop ( and function ) stops.
  • But a return is essential to creating the tree. And the for loop must continue to work.

Can you suggest another solution to do this please?


Solution

  • It's difficult to answer without seeing more codes, but you probably may handle that by postponing the return statement :

    struct sample *fn_01(void) {
        sample * s = NULL;
        for(;;) {
            switch(..) {
                case 1:
                    s = fn_02();
                    break;
                case 2:
                    s = fn_03();
                    break;
            }
            // Check s and/or do something with it. Return only when relevant
        }
    }