Skip to content

Instantly share code, notes, and snippets.

@chadaustin chadaustin/ub.md
Last active Jun 14, 2017

Embed
What would you like to do?
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.

@zeux

This comment has been minimized.

Copy link

zeux commented Jun 13, 2017

I'm assuming that CHECK_EQUAL expands to a function call if the condition is false; in this case, the compiler must assume that the function has side effects, for example it might throw - in which case you can't really elide the checks.

@chadaustin

This comment has been minimized.

Copy link
Owner Author

chadaustin commented Jun 14, 2017

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
You can’t perform that action at this time.