Vanessa Moe
Vanessa Moe

Reputation: 23

C programming: Boolean

I have a quick question regarding Boolean and its false and true values. I know that 0=false and 1=true, but according to the code I have been given as an example, it says otherwise.

Why is it equal to 0, when we want to find all the users below 23 and with a BEL nationality?

void opgave_1 (loebsdata2017 *alle_loebsdata2017 ) {
    int i = 0;
    for (i = 0; i < MAX_RYTTERE; i++) {
        if(alle_loebsdata2017[i].rytteralder < 23 &&
           strcmp(alle_loebsdata2017[i].nationalitet, "BEL") == 0)
        {
            printf("%s %s %d %s \n", alle_loebsdata2017[i].rytternavn,
               alle_loebsdata2017[i].rytterhold,
               alle_loebsdata2017[i].rytteralder,
               alle_loebsdata2017[i].nationalitet);
        }
    }
} 

Upvotes: 0

Views: 91

Answers (2)

Yunnosch
Yunnosch

Reputation: 26703

The 0 occurring in your code is not boolean.

Quoting from strcmp spec, e.g. http://en.cppreference.com/w/c/string/byte/strcmp

Return value
Negative value if lhs appears before rhs in lexicographical order.
Zero if lhs and rhs compare equal.
Positive value if lhs appears after rhs in lexicographical order.

So the comparison to 0 checks wether the string is equal to "BEL", exactly what you describe.

Upvotes: 1

tgogos
tgogos

Reputation: 25152

When

strcmp(alle_loebsdata2017[i].nationalitet, "BEL") == 0

this can be considered as:

alle_loebsdata2017[i].nationalitet is equal to "BEL"

because the strcmp() function returns 0 when the strings being compared are equal.

from:

https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm

Upvotes: 1

Related Questions