0

I have a little confusion about this statement.

if( Ql_StrPrefixMatch(strURC, urcHead) )
    {
        callback_NTPCMD((char*)strURC);
    }

The source code of Ql_StrPrefixMatch is:

    s32 Ql_StrPrefixMatch(const char* str, const char *prefix)
{
    for ( ; *str != '\0' && *prefix != '\0' ; str++, prefix++)
    {

        if (*str != *prefix) {
            return 0;
        }
    }
    return *prefix == '\0';
}

How is the if-statement evaluated to True or False based on the returns of Ql_StrPrefixMatch function, because it either returns 0 or *prefix == '\0'? Does return of 0 mean False? Please help me to explain this point. Thank you in advance

Ibrahim
  • 11
  • 1
  • 6
  • In C, all non-zero values are "true", and zero is "false". That means `if( Ql_StrPrefixMatch(strURC, urcHead) )` is equivalent to `if( Ql_StrPrefixMatch(strURC, urcHead) != 0 )`. This should have been taught by any decent book, tutorial or class. – Some programmer dude Oct 10 '22 at 07:06
  • Thank you so much. Yes I knew about Ql_StrPrefixMatch(strURC, urcHead) != 0 but confused about the above case. – Ibrahim Oct 10 '22 at 07:08
  • Also note that the function `Ql_StrPrefixMatch` either returns `0` which will be considered "false", or return the result of `*prefix == '\0'` which in itself is a boolean result which will be converted to either the integer `1` (if the condition is true) or the integer `0` (if the result if false). – Some programmer dude Oct 10 '22 at 07:09
  • Now its clear. Thank you – Ibrahim Oct 10 '22 at 07:10

3 Answers3

1

....because it either returns 0 or '\0'?

No, the second return statement uses a comparison operator, not an assignment. That returns either 0 or 1. That return value is used to evaluate the if statement.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

s32 is a signed integer. The function returns eigther 0 or 1. C then interprets this as a bool.

Why does the function return 1?
*prefix == '\0' gives a bool, which then is converted to s32.

csoeger
  • 61
  • 6
0

Yes, indeed, you are current. 0 in c means false, and also, on the other hand, NULL or '\0' also evaluates to false. You can refer to this answer for your query. So as you can guess, if(0) and if('\0') will be evaluated to the false branch of the if statement. And also, additional information: Anything non-zero value will be evaluated as true.

Tauro
  • 59
  • 7