[英]why the if condition 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;
}
為什么 if 條件總是為真?
因為'u'
在字符串中。
嘗試
ptr = strrchr(text, 'q');
看看會發生什么。
strrchr
返回指向所搜索strrchr
的指針,或者在找不到strrchr
返回NULL 。
至於:
...為什么這個 if 條件不需要任何“條件”
在 C 中,任何可以轉換為整數值的東西都可以用作條件。 例子:
int x = 42;
if (x)
{
// do something
}
這里x
是一個條件。 這和說的一樣
int x = 42;
if (x != 0)
{
// do something
}
任何非“零”的東西在 C 中都被認為是 TRUE。
這也適用於指針:
int* p = NULL;
p = whatever...;
if (p)
{
// do something isn't NULL
}
else
{
// p is NULL so do something else
}
也可以寫成:
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.