gpt4 book ai didi

c++ - 比较表达式中条件语句的基础是什么?

转载 作者:行者123 更新时间:2023-11-30 18:57:50 25 4
gpt4 key购买 nike

我对可能适用于几乎所有编程语言的条件语句感到困惑。例如这个 C++ 代码:

int main()
{
char *ptr, arr[]={'C','O','M','P','I','L','E','R','\0'};
ptr = arr;
*ptr = 'Z';
while(*ptr++)
cout << *(ptr-1);

return 0;
}

据我所知,条件语句仅在表达式为真时才执行。所以在这种情况下,这部分:

while(*ptr++)

编译器认为除 NULL 之外的所有字符都是 true。那么在这种情况下,意思是说只有 NULL 是假的吗?对角色这样做可以吗?:

if('x'){do something}

最佳答案

while(*ptr++)

将继续下去,直到 ptr 没有指向该字符串的末尾,即 \0 (空终止符),同样的语句还会递增 ptr 以指向每次运行的下一个值,所以本质上它是在说当这个条件成立时,继续前进。条件是 while ptr 仍然指向 arr 的元素;

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

<强> Reference

编辑:

But why is it accepting arguments like: while('x')? A letter 'x' is true?

不,这并不意味着字母本身是真的,它意味着它不是 NULL,即 0。这样考虑。

while('x')

相当于说

while('x'!=0)    // so that is perfectly acceptable and understandable

编辑2:

这是一个更简单的例子,以便您能够更好地理解

#include <iostream>


int main()
{
int x=0;

if(x)
{
cout<<"If this is shown, x was not 0.";
}
if(x==0)
{
cout<<"so does it mean x is true? no: It means your condition 'x==0' is true";
}
}

关于c++ - 比较表达式中条件语句的基础是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19238699/

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