ReadingLab / Discussion-for-Cpp

C++ 中文讨论区
MIT License
88 stars 63 forks source link

6.48对assert的使用为什么不对? #47

Closed pyb1993 closed 8 years ago

pyb1993 commented 8 years ago

当因为输入无效而终止循环那么assert(cin)将报错,否则输入就是sought,这种情况assert(cin)将跳过,这和assert(s==sought)的效果是一样吧? assert(cin)怎么可能一直为true呢?不明白这句话的意思

pezy commented 8 years ago

放便给出一个测试用例,让 assert(cin) 为 false 吗?

pyb1993 commented 8 years ago

在vs2013上输入cltr+z时不就代表终止输入吗?assert(cin)为false,代表循环不是因为输入为sought而终结的.否则程序将一直循环直到输入为sought,此时输入是有效的.

pezy commented 8 years ago

明白你的意思了.

原答案的表述的确有点问题. 但这里 assert 的用法的确是有问题的. 因为 assert 用来检查的, 是一定不会发生的事情. 如原文所述:

The assert macro is often used to check for conditions that “cannot happen.”

就如你给出的例子, 输入 EOF, 是很正常的用户行为, 此时去断言 cin, 是毫无意义的. 而答案所说, 用 assert(s == sought) 更好, 其实遗漏了 cin 无效的情况. 用 assert(!cin || s == sought); 要更好一些.

pyb1993 commented 8 years ago

终于弄明白“不能发生的情况“这句话的内涵了,谢谢您啦。