gpt4 book ai didi

c - 如果在 if 条件字符串中给出它被视为 true 但它返回什么?

转载 作者:太空宇宙 更新时间:2023-11-04 07:15:55 26 4
gpt4 key购买 nike

为什么 if 条件中的字符串文字被视为 true?

if("whatiamreturning")
//this is true. I want to know y?

基于以上,这里发生了什么?

#‎include‬<stdio.h>
void main() {
static int i;
for(;;) { //infinite loop
if(i+++"The Matrix")
// what is happening in the above line?
printf("Memento");
else
break;
}
}

最佳答案

if("whatiamreturning") 

相当于

if (1)

这是因为 "whatiamreturning" 是一个 char [],它在 内部衰减为一个非 NULL char const*如果()。在 bool 表达式的上下文中,任何非 NULL 指针的计算结果都是 true

线

if(i+++"The Matrix") 

可以简化为:

if( (i++) + "The Matrix") 

在循环的第一次迭代中,i 的值为0。因此,(i++) + "The Matrix" 的计算结果为 "The Matrix"

在循环的第二次迭代中,i 的值为1。因此,(i++) + "The Matrix" 的计算结果为 "he Matrix"

但是,循环永远不会结束并进入未定义行为的领域,因为 (i++) + "The Matrix" 永远不会评估为 0i 不断增加。

也许他们打算使用:

  if(i++["The Matrix"])

这将允许 if() 中的表达式在 10 次迭代后为 0

更新

如果您正在遵循其他人的代码,请远离他们编写的任何其他内容。 main 函数可以清理为:

int main() {
char name[] = "The Matrix";
int i = 0;
for( ; name[i] != '\0'; ++i )
{
printf("Memento\n");
}
}

关于c - 如果在 if 条件字符串中给出它被视为 true 但它返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24642397/

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