简体   繁体   中英

Terminating a recursive function in C

int postOrder(struct node* root, char organ[], char bt[], int* val){

    if(root != NULL) {
        postOrder(root->left, organ, bt, val);
        postOrder(root->right, organ, bt, val);
        if(strcmp(root->organ.organname, organ) == 0){
            if(strcmp(root->organ.bloodtype, bt) == 0){
               if(val == 0){
                printf("%s\n", root->organ.name);
                val = 1;
                }
            }
        }
    }
}

I'm trying to terminate this recursive function right after the first print. My idea originally was to pass in a decimal pointer 'val' and set that to 1 when I wanted to terminate the function. The thought process is it would change the value outside of the function so all of the previous calls would have the updated pointer, but I don't think that's how it works in this setup.

This function searches post the Post Orderly through a binary tree.

Use *val . val is just a pointer. You want the value of it.

Since currently your function does not return anything, you can change it to return 1 if it has printed anything, and return 0 if it does not. This way you wouldn't need to pass val pointer (which you are not using correctly anyway).

int postOrder(struct node* root, char organ[], char bt[]){
    if(root == NULL)  return 0;
    if (postOrder(root->left, organ, bt, val)) return 1;
    if (postOrder(root->right, organ, bt, val)) return 1;
    if (strcmp(root->organ.organname, organ) == 0 && strcmp(root->organ.bloodtype, bt) == 0) {
        printf("%s\n", root->organ.name);
        return 1;
    }
    return 0;
}

val is a pointer to an integer so you will need to dereference it when setting or getting its value.

Try:

if(*val == 0) { *val = 1; ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM