Definition: Undefined behavior

In computer science, undefined behavior is when the consequence of running a program is unpredictable. For instance, in the code below, bool flag could be initialized to be either false or true depending on the specifications of the particular build of your compiler.

#include <iostream>
using namespace std;
int main() {
bool flag;
if (flag)
cout << "True";
else
cout << "False";
return 0;
}

The result is unpredictable and, in some instances such as division by zero, the result may even be undefined. In these situations, the compiler will decide what to do. Programs with undefined behaviors may not work as intended on particular compilers depending on their specification. This usually results in errors such as crashing the program or corrupting data.

These errors can be confounding, so it best to be aware of code that may result in undefined behavior. Fortunately, many modern languages will not let you write code that could result in undefined behavior. C and C++ compilers compromise on checking for undefined behaviors in favor of optimizing the program for speed.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved