简体   繁体   中英

How to initialize value to function whose return type is boolean?

I want to initialize true for checkForBST(node* rootptr) function. What should i do? I know variable initialization but I always get confused in function initialization. Below is my checkForBST(node* rootptr) function:

bool checkForBST(node* rootptr){
        queue <node*> Q;
        int parent;
        int child1;
        int child2;
        node* parentadr;
        Q.push(rootptr);
        do{
          parent=Q.front()->data;
          parentadr= Q.front();
          if(Q.front()->left !=NULL) {child1= Q.front()->left->data;} else{child1=-1;}
          if(Q.front()->right !=NULL) {child2= Q.front()->right->data;} else{child2=-1;}
          Q.pop();
          if(child1>child2){return false;}
          if(parentadr->left != NULL){Q.push(parentadr->left);}
          if(parentadr->right != NULL){Q.push(parentadr->right);}
        }while(!Q.empty());
    }

I'm not sure if I fully understand your question, but if you want to initialize the return type for the function to return 'true', then you would just create a local function variable, initialize it to true, and return that variable at the end.

bool checkForBST(node* rootptr) {
    bool returnVal = true;

    ....

    return returnVal;

}

The title of your question sounds more like you're trying to assign a variable to a function (function pointer variable). To do that, you would do something like this:

bool checkForBST(node* rootptr) { 
    ...
} 

void (*my_variable)(node*) = &checkForBST; 

Add the 'return true;' statement at the end:

bool checkForBST(node* rootptr){
    queue <node*> Q;
    int parent;
    int child1;
    int child2;
    node* parentadr;
    Q.push(rootptr);
    do{
        parent=Q.front()->data;
        parentadr= Q.front();
        if(Q.front()->left !=NULL) {child1= Q.front()->left->data;} else{child1=-1;}
        if(Q.front()->right !=NULL) {child2= Q.front()->right->data;} else{child2=-1;}
        Q.pop();
        if(child1>child2){return false;}
        if(parentadr->left != NULL){Q.push(parentadr->left);}
        if(parentadr->right != NULL){Q.push(parentadr->right);}
    }while(!Q.empty());
    return true;
}

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