开发者

how to understand "return *test== ‘\0’;"

开发者 https://www.devze.com 2023-02-15 00:20 出处:网络
There is a code snippet, int matchhere(char *regexp, char*text) { /* do sth */ 开发者_开发知识库return*test== \'\\0\';

There is a code snippet,

int matchhere(char *regexp, char  *text)
 {
    /* do sth */
 开发者_开发知识库   return    *test== '\0';
 }

I do not understand what does

return    *test== '\0';

mean. Or what it will return? How does "==" function here?


compare *test to '\0', return 0 if inequal, return 1 if equal.


The *test part reads the first character for the C string (a C string is merely a bunch of characters starting at a given address, and the *foo operator looks at that address which happens to contain the first character). By definition, a C string ends with a null byte ('\0' or simply 0).

So this tests whether the first character is the end-of-string character. Or in other words: it tests whether the string is empty. That comparison result (1 if empty, 0 if non-empty) is returned.


It fails to compile because "test" is not the same as "text", and because there is no such type Int in C.

If the typos were fixed, it'd see whether the first letter of the buffer pointed to by text is the NULL character -- i.e. it returns 1 if the buffer is empty, and 0 otherwise.


It checks if the character pointed by text pointer equals '\0' character (string-terminating character).


*test means the contents of the test pointer, which is a char.

*test == '\0' just compares that character to the null character.

return *test == '\0' means return the result of that comparison.

So basically, if test points to a null-character then matchhere() will return true, otherwise false.


It checks if *test is an empty string, in that case return a different from zero value


*test represents the first character of a string.

== is the equality operator.

'\0' is the null character, which in C represents the end of a string.

*test== ‘\0’ is a logical expression which returns true whenever the string is empty.

The whole instruction returns that logical result to the caller.


The statement

return *text == '\0';

is equivalent to

return text[0] == '\0';

which is also equivalent to

return text[0] == 0;

In each case, it's comparing the first character of the string pointed to by text to 0, which is the string terminator, and returning the result of the comparison. It's equivalent to writing

if (*text == '\0') // or *text == 0, or text[0] == 0, or !*text, or !text[0]
  return 1;
else
  return 0;

Another equivalent would be

return !*text; // or !text[0]

which will return 0 if *text is non-zero, 1 otherwise, but that's pushing the bounds of good taste.

0

精彩评论

暂无评论...
验证码 换一张
取 消