[英]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.嗨,我不明白为什么这个 if 条件不需要任何“条件”并且总是正确的。
#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?
为什么 if 条件总是为真?
Because 'u'
is in the string.因为
'u'
在字符串中。
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. strrchr
返回指向所搜索strrchr
的指针,或者在找不到strrchr
返回NULL 。
As for:至于:
... why this if condition don't need any "condition"
...为什么这个 if 条件不需要任何“条件”
In C anything that can be converted to an integer value can be used as a condition.在 C 中,任何可以转换为整数值的东西都可以用作条件。 Example:
例子:
int x = 42;
if (x)
{
// do something
}
Here x
is a condition.这里
x
是一个条件。 It is the same as saying这和说的一样
int x = 42;
if (x != 0)
{
// do something
}
Anything that isn't "zero" are considered TRUE in C.任何非“零”的东西在 C 中都被认为是 TRUE。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.