简体   繁体   中英

why the if condition is always true?

hi, i don't understand why this if condition don't need any "condition" and is always true.

  #include <string.h>
    #include <stdio.h>

    int main() {
        char text[] = "I learn C programming because it’s fun";
        char *ptr, c = 'u';
        ptr = strrchr(text, c);

        if (ptr)
        {
            printf("The position of ’%c’ is: %d\n", c, ptr-text);
        }

        printf("The character was not found\n");
        return 0;
    }

why the if condition is always true?

Because 'u' is in the string.

Try

ptr = strrchr(text, 'q');

and see what happens.

strrchr returns a pointer to the character searched for or NULL when the character isn't found.

As for:

... why this if condition don't need any "condition"

In C anything that can be converted to an integer value can be used as a condition. Example:

int x = 42;
if (x)
{
    // do something
}

Here x is a condition. It is the same as saying

int x = 42;
if (x != 0)
{
    // do something
}

Anything that isn't "zero" are considered TRUE in C.

This goes for pointers as well:

int* p = NULL;
p = whatever...;
if (p)
{
    // do something isn't NULL
}
else
{
    // p is NULL so do something else
}

which can also be written as:

int* p = NULL;
p = whatever...;
if (p != NULL)   
{
    // do something isn't NULL
}
else
{
    // p is NULL so do something else
}

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