简体   繁体   中英

Why ideone.com does this?

I was recently trying to run this code in 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. 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

When I tried to execute the same code on Visual Studio, I got an exception (which was expected). 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.

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. You definitely should not have UB in your code, because only then you can reason about it. But by leaving the behavior undefined, the C++ standard gives implementations great optimization opportunities. They don't need to constantly add checks that raise exceptions when we as programmers blunder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM