在 C 中使用 'continue' 和基于布尔的语句

Using 'continue' with boolean-based statements in C

对于那些不明白的人 - 我知道这不是一个好的代码应该是什么样的......这个棘手问题的目的是编写没有 if 语句的代码为了练习布尔逻辑...

我正在尝试用 C 语言解决一个问题,该问题限制程序员使用 if/else/switch 语句。 也不能使用三元运算符。 这个想法是使用基于布尔的逻辑语句来获取 "wanted path"。 即 - 而不是:

if (1 > 0)
   printf("TRUE")
else
   printf("FALSE")

我会使用:

bool res = true;
res = (1 > 0 && printf("TRUE")) || printf("FALSE")

(这是大概的思路,用boolean语句处理逻辑来操作不同的action。 我 运行 遇到的唯一问题是替换看起来有点像这样的部分(如果 A 等于 B,我希望程序跳过循环的某个部分):

while (...)
{
   if (A == B)
       continue;
   //code
}

你知道这是否可以在不使用 if/else/switch 语句的情况下执行吗?

谢谢!!

if (1 > 0)
   printf("TRUE")
else
   printf("FALSE")

I would use:

bool res = true;
res = (1 > 0 && printf("TRUE")) || printf("FALSE")

如果我看到我团队中的任何程序员编写了这样的代码,我就会解雇 him/her。

为什么?您的版本不是人类可读的,它容易出错并且几乎不可调试。

Do you know if this is possible to execute without using if/else/switch statements?

使用 gcc 扩展 statement expressions 你可以这样做:

int main() {
    int A, B;
    while (1) {
        A == B && ({continue;0;});
    }
}

请不要这样做,也请不要这样做 res = (1 > 0 && printf("TRUE")) || printf("FALSE")。只写 ifs.

相当于你的

while (condition)
{
   foo();
   if (A == B)
       continue;
   bar();
   baz();
}

while (condition)
{
   foo();
   (A != B) && bar();
   (A != B) && baz();
}

这假设 bar() 不会更改 AB。如果是,请使用临时变量:

while (condition)
{
   foo();
   bool cond = A != B;
   cond && bar();
   cond && baz();
}

假设可以使用 state 变量然后

while (...)
{
   if (A == B)
       continue;
   //code
}

可以实现为

state = true ;
while ( ... ) {
   ...
   while ( a == b ) {
       state = false ;
       break ;
   } ;
   while ( !state ) {
       // code here
       break ;
   } ;
}

或者在允许的情况下减少混乱:

while (...)
{
   state = A == B ;
   while ( state ) {
       //code here
       break ;
   } ;
}

由于必须进行双重测试而造成的性能损失相对较小。

旁注:在我的本科学习中(很多年前),我记得听过一个讲座,该讲座解释了所有控制流命令(if、while、do {} while、switch,goto 除外),可以使用 while 来实现。我希望我能为此找到 reference/proof。这是关于代码验证的讲座的一部分。