简体   繁体   中英

C - Check If All Values of Struct Array Return Same Values

I want to check if all values of a struct array hold the same value for the purpose of hiding "deleted" entries in the struct array.

My struct looks like this:

struct spawnedObject {
    Hash objHash;
    Object obj;
    char* displayname;

    int invisibility;
    Vector3 position;

    int deleted; // 1=deleted and hidden, 0=should be listed and available
};

And I want to check if deleted is true for all entries in the struct. When they're all true, have the else display the empty text.

I have tried looping all deleted values and increasing an int when a value is set to 1 like so:

void objectManagerMenu() {
    objectVar = 0;
    int inc = 0; //store deleted entries count

    // loop through all entries. if entry deleted, increase.
    for (int i = 0; i < objectCount; i++) {
        if(spawnedObjects[i].deleted) inc++;
    }

    // check if there either are no entries, or if theyre hidden. if all stored entries are hidden, fallback to else. this is where it goes wrong.
    // problem: does not seem to fallback to else.
    if(objectCount != 0 || objectCount != inc) {
        for (int i = 0; i < objectCount; i++) {
            if(!spawnedObjects[i].deleted) { // remove hidden items from list
                char buffer[150];
                sprintf(buffer, "[ %i ] %s", i, spawnedObjects[i].displayname);

                menu.option(buffer).call(objectItemVar, i).submenu(objectItemMenu);
            }
        }
    } else {
        menu.option("Empty");
    }
}

Doesn't seem to work as nothing is being displayed.

Does anybody have a suggestion how I can do this a smarter way?

The problem is your || in the if statement like stated int the comment.

objectCount != 0

most likely returns true

objectCount != inc

returns false, because the menu is empty (in your current scenario which you are tryining to test)
by that the if statement will always be true (if your object count is bigger then 0) and thus else is never executed. change the || to &&

Why
|| returns true if at least one of the statements gives true.
&& returns true only when both are true and that is what you want

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