[英]using a while loop with multiple conditions
当我需要使用多个条件时,我总是感到困惑。 我相信这是正确的。
1 and 1 = 1
1 and 0 = 0
1 or 1 = 1
1 or 0 = 1
有一些我需要处理while循环的事情吗? 如果语句在多个条件下看起来总是像我期望的那样运行。 是否有遵循的良好经验法则?
像这儿。 由于我通常尝试|| 而且我第一次使用&&似乎从未奏效。 但是我当然需要一个||。 在这种情况下,仅仅是因为我做了与平时相反的事情。
const char *s = buffer;
parser_comment_level = 0
while (ispunct((unsigned char)*s) || parser_comment_level != 0)
{
}
我想将以上内容更改为。 那是正确的还是我需要使用&&? 使用括号会是个好主意吗?
const char *s = buffer;
parser_comment_level = 0
while (ispunct((unsigned char)*s) || parser_comment_level != 0 || (unsigned char)*s != '\0')
{
}
因此,要剖析while (ispunct((unsigned char)*s) || parser_comment_level != 0 || (unsigned char)*s != '\\0')
我们需要了解子表达式之间的相互作用。 如果任何子表达式为true,则必须继续循环,因此,如果(unsigned char)*s != '\\0'
,则必须继续循环。 因此,看起来也取决于*s
ispunct((unsigned char)*s)
似乎永远不会重要。 这是表达错误的线索。
while ((ispunct((unsigned char)*s) || parser_comment_level != 0) && (unsigned char)*s != '\0')
好多了。 现在,点击null终止符将退出循环,但是前面的表达式也将退出。
简而言之,当任一子表达式都应退出循环时,请使用&&
,而||
当任一子表达式应继续循环时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.