Skip to content

Instantly share code, notes, and snippets.

@chadaustin
Last active June 14, 2017 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadaustin/2c249cb850619ddec05b23ca42cf7a18 to your computer and use it in GitHub Desktop.
Save chadaustin/2c249cb850619ddec05b23ca42cf7a18 to your computer and use it in GitHub Desktop.
Undefined Behavior in Unit Test

Imagine an API like this:

bool double_if_positive(float input, float* output) {
  if (input > 0) {
    *output = input * 2.0f;
    return true;
  } else {
    return false;
  }
}

And a unit test like this:

extern float var;
TEST(test) {
  float output;
  CHECK_EQUAL(true, double_if_positive(var, &output));
  CHECK_EQUAL(var * 2.0f, output);
}

I believe an optimizing compiler would be able to elide both unit test checks, because accessing is output is only defined behavior if the return value is true, therefore the return value must be true.

EDIT: Actually, the second wouldn't get elided.

@chadaustin
Copy link
Author

Yeah, if the function may have arbitrary effects, then yeah. A lot of these things depend on how far the compiler can see.

The unstated assumption in my example is that CHECK_EQUAL continues executing the test in the case of a failure (as is true in UnitTest++, for example).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment