C++Bare布尔表达式(不包含if、while或其他语句)

C++ Bare Boolean Expressions (without an if, while or some other statement)

本文关键字:while 其他 语句 if 布尔表达式 包含 C++Bare      更新时间:2023-10-16

我发现以下代码可以解决这个在线C++编码问题:

"问题:编写一个程序,在不使用任何条件结构的情况下找到任意数组中最大的元素:禁止{if/if-else/switch/for/while/do/?:-运算符}。"

# include <iostream>
int findMax(int * array, size_t size)
{
    int max, other;
    size > 2 && (other = findMax(array + 1, size - 1)) || (other = array[1]);
    other > array[0] && (max = other) || (max = array[0]);
    return max;
}
int main()
{
    int array[] = {3, 1, 4, 15, 9, 2, 6, 5, 35, 8, 97, 93, 23, 84, 62, 64, 33, 83, 27, 950, 28, 841, 971, 69, 39, 937, 510};
    std::cout << findMax(array, sizeof(array) / sizeof(array[0])) << std::endl;
    return 0;
}

我的问题:我们如何在C++中做这样的事情?

size > 2 && (other = findMax(array + 1, size - 1)) || (other = array[1]);

我在C++方面的经验有限,在java中还没有见过这样的东西。有人能解释一下我们如何在没有if、while或其他语句的情况下让布尔表达式裸运行吗。我在谷歌上搜索了很多,但找不到任何有用的东西。非常感谢。


编辑:谢谢大家的回复。我理解短路的概念。但通常我会这样使用它:

1. if (boolean1 && boolean2 || boolean3)
2.  // do sth;
3. while(boolean1 || boolean2)
4.  // loop;
5. return boolean1 && boolean2;

现在我更像是一个java用户。所以我在java代码中尝试了如下操作:

size > 2 && (other = findMax(array + 1, size - 1)) || (other = array[1]);

但它只是给出了一个编译时错误。我想java在这些规则上更严格。不管怎样,再次感谢。

这叫做短路。http://en.wikipedia.org/wiki/Short-circuit_evaluation

基本上,如果您有一个&&||运算符,如果在检查下一个值时没有意义,它就永远不会执行。

考虑以下语句:

isCondition1Fulfilled(a) || isCondition2Fulfilled(a)

如果isCondition1Fulfilled(a)为真,那么不管怎样,整个表达式都为真,所以调用isCondition2Fulfilled(a)只是浪费时间。所以它从来没有被调用过。

这是另一个:

isCondition3Fulfilled(a) && isCondition4Fulfilled(a)

如果isCondition3Fulfilled(a)为false,则调用isCondition4Fulfilled(a) 没有意义

你的程序利用了它,例如:

size > 2 && (other = findMax(array + 1, size - 1)) || (other = array[1]);

如果size小于或等于2,则从不调用其余部分。如果不是,但findMax(array + 1, size - 1)是正的,则不调用(other = array[1])

剩下的自己想:)

EDIT(对OP中EDIT的响应):

在这种情况下,Java确实要严格得多。在C/C++中,几乎任何东西都可以进入if语句:int、指针、字符串、常量、char等。但正如我们与@Keith Thompson讨论的那样,您可以将任何类似的语句放在一行代码中。它将被评估并立即丢弃。

相关文章: