简体   繁体   English

为什么ideone.com这样做?

[英]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.

相关问题 为什么这个C ++代码在ideone.com上获得SIGILL? - Why does this C++ code get SIGILL on ideone.com? C++ 正则表达式在 ideone.com 上匹配,但在 Android NDK 构建中不匹配 - C++ regex matches on ideone.com but not in Android NDK build 程序在Visual Studio 2012中运行,但不在ideone.com中运行 - Program runs in Visual Studio 2012 but not ideone.com 这段代码可以在代码块中完美运行,但在ideone.com上给出了运行时错误 - This code is running perfectly in codeblocks but giving a runtime error on ideone.com 如何为ideone.com中的代码文件指定自定义文件名? - How can I give a custom file names to a code file in ideone.com? 为什么要在Ideone上编译? - Why does this compile on Ideone? 当我在ideone.com上运行时,在阶乘中尾随零。 甚至SPOJ也不接受 - trailing zeros in a factorial.when i run it on ideone.com i'm getting runtime error with infinite output. Even SPOJ is also not accepting 为什么这会在ideone和visual studio中显示运行时错误,但在代码块中却没有? - why this shows runtime error in ideone & visual studio but not in code blocks? 为什么COM IUnknown :: Release的实现有效? - Why does this implementation of COM IUnknown::Release work? 为什么GCC 4.7.0在此代码上给我一个段错误,而在线ideone(gcc 4.5.1)没有给我? - Why is gcc 4.7.0 giving me a segfault on this code while online ideone(gcc 4.5.1) doesnt?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM