"if" c++ 中的语句不会从左到右评估条件
"if" statement in c++ doesn't evaluate conditions from left to right
我指的是问题“"IF" argument evaluation order?”,以了解 c++ 中 "if" 语句的求值顺序。
以下代码中 if 语句中条件的计算顺序错误。
#include <iostream>
using namespace std;
int main()
{
int t = 0;
if((1 / t) == 1 && t != 0)
{
cout << "0" << endl;
}
cout << "1" << endl;
return 0;
}
结果是1而不是浮点数异常
被零除是未定义的行为。什么事都有可能发生。
If the second operand of / or % is zero the behavior is undefined.
除以零并不能保证每次程序都会抛出运行时错误。这就是为什么除以零是未定义的行为。
如 C 标准所述;
The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behaviour is undefined.
对于 C++ (03-5.6.4);
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division
of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise
(a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative;
if not, the sign of the remainder is implementation-defined
我指的是问题“"IF" argument evaluation order?”,以了解 c++ 中 "if" 语句的求值顺序。
以下代码中 if 语句中条件的计算顺序错误。
#include <iostream>
using namespace std;
int main()
{
int t = 0;
if((1 / t) == 1 && t != 0)
{
cout << "0" << endl;
}
cout << "1" << endl;
return 0;
}
结果是1而不是浮点数异常
被零除是未定义的行为。什么事都有可能发生。
If the second operand of / or % is zero the behavior is undefined.
除以零并不能保证每次程序都会抛出运行时错误。这就是为什么除以零是未定义的行为。
如 C 标准所述;
The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behaviour is undefined.
对于 C++ (03-5.6.4);
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined