如果要简化语句,该如何?

How can this if statement be simplified?

本文关键字:语句 如果      更新时间:2023-10-16

我正在使用clion IDE来编码我的C 项目。有时,IDE试图比我更聪明,并给我建议。在代码检查期间(通过CLION(有一个简单的问题。它说,即使我认为这是我能想到的最简单的形式,也可以简化以下代码:

代码:

    if (node.first >= 0 && node.first <= 45 &&
    node.second >= 0 && node.second <= 30)
    return true;
    else
    return false;

假设节点是类型std::pair<int, int>

我从Clion IDE获得的建议如下:

代码检查评论:

Inspection info: This inspection finds the part of the code that can be simplified, e.g. constant conditions, identical if branches, pointless boolean expressions, etc.

您认为这可以简化吗?

clion暗示您这个位...

if (node.first >= 0 && node.first <= 45 &&
    node.second >= 0 && node.second <= 30)
    return true;
else
    return false;

可以重新编写为

return node.first  >= 0 && node.first  <= 45 &&
       node.second >= 0 && node.second <= 30;

由于在控制语句中用作条件的表达式显然具有自然转换为true和false。