gpt4 book ai didi

c - 为什么if条件总是为真?

转载 作者:行者123 更新时间:2023-11-30 16:06:22 24 4
gpt4 key购买 nike

嗨,我不明白为什么这个 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?

因为'u'在字符串中。

尝试

ptr = strrchr(text, 'q');

看看会发生什么。

strrchr 返回指向所搜索字符的指针,如果未找到该字符,则返回 NULL

至于:

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

在 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
}

关于c - 为什么if条件总是为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59975817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com