CS253: Software Development with C++

Spring 2021

Undefined

Undefined Behavior

Definition

The term undefined, or undefined behavior, means that no restrictions are placed on the behavior of a program in certain circumstances. It is not the same as an error condition.

Example

int main() {
    return 1/0;
}
c.c: In function 'main':
c.c:2: warning: division by zero
SIGFPE: Floating point exception

The C and C++ standards says that a program that divides by zero invokes undefined behavior. This means that an implementation places no restrictions on the behavior of such a program. That is, it may do anything, including but not restricted to:

Those aren’t all good possibilities, but, since undefined behavior puts no restrictions on possible actions, they are all allowed by the C and C++ standards.

Why

Why allow undefined behavior? To not restrict implementations. The C and C++ standards realize that requiring any particular behavior would, for some computer architectures, result in unnecessarily slow or large programs. Instead, the standards merely state that division by zero invokes undefined behavior, so that each implementation can do whatever is reasonable for those circumstances.

Another Example

A homework programming assigment might specify:

  1. If the input is two numbers, subtract them.
  2. If the input is three numbers, add them.
  3. More than three numbers results in undefined behavior.

The third line is another way of saying that we don’t care what happens if there are more than three numbers. These would all be ok responses, if four numbers are given:

Testing

What will a TA or a grader do in an undefined behavior situation? They will ignore it. They won’t test it; since any behavior is acceptable, why bother writing a test that can never fail?