[英]Why ideone.com does this?
I was recently trying to run this code in ideone.com... 我最近试图在ideone.com中运行此代码...
#include <iostream>
#include <string>
using namespace std;
int getVal(string name)
{
if (name == "Devashish") return 0;
return 1;
}
int main()
{
cout << 5 / getVal("Devashish");
return 0;
}
Interestingly enough, this code didn't throw any exception and printed 5 in output. 有趣的是,此代码未引发任何异常,并在输出中打印了5。 The code is intentionally written to produce an exception. 故意编写代码以产生异常。 Here is the ideone link to successful compilation and execution of the buggy code: http://ideone.com/ogDzDU 这是成功编译和执行越野车代码的ideone链接: http ://ideone.com/ogDzDU
When I tried to execute the same code on Visual Studio, I got an exception (which was expected). 当我尝试在Visual Studio上执行相同的代码时,出现了一个异常(这是预期的)。 Just curious. 只是好奇。 Why ideone behaved so? 为什么二烯酮如此表现? Is it a bug in their compilers or some other program? 这是他们的编译器或其他程序中的错误吗?
Dividing by zero in a C++ program has strictly undefined behavior. 在C ++程序中被零除具有严格未定义的行为。
It means no one can say how your program will behave. 这意味着没有人能说出您的程序如何运行。 It could raise an exception, but there's no guarantee it will. 它可能会引发异常,但不能保证会。 It could also run smoothly and leave you perplexed, as you are now. 它也可以像现在一样平稳运行,并让您感到困惑。
That is the nature of UB. 那是UB的本质。 You definitely should not have UB in your code, because only then you can reason about it. 您绝对不应在代码中包含UB,因为只有这样您才能对此进行推理。 But by leaving the behavior undefined, the C++ standard gives implementations great optimization opportunities. 但是通过保留行为未定义,C ++标准为实现提供了巨大的优化机会。 They don't need to constantly add checks that raise exceptions when we as programmers blunder. 当我们作为程序员大失所望时,他们不需要不断添加引发异常的检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.