l4m2
l4m2

Reputation: 1157

Why assert(0) in released version is NOT undefined behavior?

. assert(x) should mean that x is true so compliers should have right to use this info to optimize.

For example,

char const* week(int n) {
    assert (n>=0 && n<7);
    switch (n) {
        case 0: return "Sunday";
        ...
        case 6: return "Saturday";
    }
    return 0;
}

can be optimized into

char const* week(int n) {
    char const* const* const x = {"Sunday", ..., "Saturday"};
    return x[n];
}

and remove the CMP n, 7

Upvotes: 0

Views: 450

Answers (2)

supercat
supercat

Reputation: 81179

The purpose of an assert directive is to increase the likelihood that an unexpected condition will be detected. Having a compiler use false assertions for dead path elimination rather than trapping would cause them to have the opposite effect. For example...

int test1(int x, int *arr)
{
  if (x < 10) 
    { arr[x]++; return 0; }
  else
    return -1;
}
void test2(int x, int *arr)
{
  assert(x < 10);
  if (test1(x, arr))
    fprintf(stderr, "test1() was unhappy!");
}

If code is generated for the asserts, calls with values of x greater than 10 will get reported. Such calls will also generate diagnostic output if asserts simply do nothing. If asserts were used for dead-path elimination, however, a compiler might stifle all of the checks that x was less than 10, thus causing such a condition to go undetected.

It might be useful to have a version of assert which a compiler could process or not at its leisure, since in some cases adding code to handle an assert would relieve a compiler from having to handle the conditions downstream. Having an assert trigger dead path elimination without a trap, however, seems like a really bad idea.

Upvotes: 0

sheikh_anton
sheikh_anton

Reputation: 3452

I'm not shure what you mean by 'released version', but assert is a macro, and it defined somehow like:

#ifdef NDEBUG
#define assert(condition) ((void)0)
#else
#define assert(condition) /*implementation defined*/
#endif

So if your released version compliled with -DNDEBUG, it just doesn nothing, why should it be undefined behaviour?

Upvotes: 5

Related Questions