我正在通过阅读 Stroustrup 的“使用 C++ 的原理和实践”来学习 C++。
在关于前置条件和后置条件的部分中,有以下函数示例:
int area(int length, int width)
// calculate area of a rectangle;
// pre-conditions: length and width are positive
// post-condition: returns a positive value that is the area
{
if (length<=0 || width <=0)
error("area() pre-condition");
int a = length*width;
if (a<=0)
error("area() post-condition");
return a;
}
让我困惑的是这段代码的任务:
Find a pair of values so that the pre-condition of this version of area holds, but the post-condition doesn’t.
是否存在前置条件可以但后置条件不行的整数值?
最佳答案
Are there such possible values for integer that pre-conditions is ok but post-condition not?
是的,有许多输入值可能导致后置条件失败。如果例如
int a = length*width;
溢出正int
range ( std::numeric_limits<int>::max()
) 并且编译器实现在这种情况下产生一个负值。
正如其他人在回答中指出的那样,length*width
的情况超出 ]0-std::numeric_limits<int>::max()[
的范围实际上是未定义的行为,并且后置条件只会变得无用,因为可能需要为 a
预期任何值.
解决此问题的关键点在 @Deduplicator 中给出的answer ,前置条件有待改进。
作为 Bjarne Stroustrup 的推理举个例子:
我假设他想指出这种未定义的行为可能会导致后置条件中出现意外的负值,并且对于与前置条件检查的幼稚假设会导致令人惊讶的结果。
关于c++ - 乘以负值的正整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34545445/