类似的断言语句给出不同的结果

similar assert statements giving different results

在下面的代码中:

#include <iostream>
#include <assert.h>
int main()
{
    int a,b;
    cin>>a>>b;
    char c,d;
    cin>>c>>d;
    assert ((a==b,a*b==9,c==d));
    assert ( a==b && a*b==9 && c==d );
}

如果你:

  1. 输入不同的整数或不同的字符,第一个断言语句中止程序。 (应该如此)。
  2. 但是,如果您在此代码中输入相等的整数(3 除外)和相同的字符,第一个断言语句不会中止程序,但第二个断言语句会。

第一个 assert 语句是否弱或者我对 assert 语句有什么不了解的地方?

a==b,a*b==9,c==d 是逗号表达式。对于 built-in comma operator:

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins

The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand, E2.

它return作为它的return值的最后一个操作数,即c==da==ba*b==9 得到评估,但他们的结果被丢弃。所以 assert ((a==b,a*b==9,c==d)); 实际上只检查 c==d

另一方面 assert ( a==b && a*b==9 && c==d ); 检查所有条件;通过 && 连接的都必须是 true 才能通过检查。

1. input different integers or different characters, the first assert statement aborts the program. (as it should).

一般表达式中逗号运算符的含义

e1 , e2

is - 计算子表达式 e1,然后计算 e2;表达式的值是 e2.

的值

所以,表达式的值

a==b,a*b==9,c==d

的值
c==d

当您在 assert() 中使用此表达式时,如果 c==d 导致 false,无论 ab 的值如何,assert() 导致程序终止。

2. But , if you input equal integers (other than 3) and same characters in this code, the first assert statement doesn't abort the program, however the second assert statement does.

逻辑与运算expr1 && expr2采用短路行为。对于逻辑短路,第二个操作数 expr2 仅在结果未完全由第一个操作数 expr1 确定时才计算。 也就是说,如果 expr1 符合逻辑 0(假),则不会评估 expr2

在第二个给出的表达式中assert()

a==b && a*b==9 && c==d

您有 a*b==9 以及 a==bc==d。因此,仅当给定输入 3ab 以及相同字符值输入到 cd 时,此表达式才会导致 true 否则此表达式导致 false,断言导致程序终止。