首页 > 解决方案 > 检查 XOR 是否也适用于语句,以及 C++ 中的 OR

问题描述

目前,如果元素是声明的开始或语句的开始,我有以下函数返回布尔值。

bool start_of_block_element() {
     return start_of_declaration() || start_of_statement();

我需要检查这些的异或是否也为真并输出一个布尔值。我不确定如何将它们组合在一起。如果 XOR 和 OR 都返回 true,它应该返回 true

我的猜测是:

bool start_of_block_element() {
    return ( 

      (start_of_declaration() ^ start_of_statement() ) && ( start_of_declaration() || start_of_statement() )

    );
}

这是正确的方法吗?

标签: c++syntaxcompiler-constructionxorbitwise-xor

解决方案


假设bool D = start_of_declaration()bool S = start_of_statement()

你想要D || S == trueD ^ S == true。所以基本上,

D | 小号 | 返回
--+---+----
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 0

任何给出此真值表的运算符都将满足您的要求,因此请使用具有此真值表的运算符:

return start_of_declaration() != start_of_statement()

推荐阅读