glglgl
glglgl

Reputation: 91129

"Undefined behaviour" always undefined?

There are may things in C which cause UB.

Most of them are ok to do so, but there are several ones where implementation-defined behaviour would be more logical. Let me have an example:

Concerning the << operator,

If E1 has a signed type and nonnegative value, and E1 × 2 E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

That means that

signed char r = 0x40;
r <<= 2;

is UB where IB would IMO be more logical.

Is an implementation allowed to define what happens here?

Upvotes: 3

Views: 127

Answers (3)

ouah
ouah

Reputation: 145899

The problem is:

signed char r = 0x40;
r <<= 2;

is not undefined behavior.

C says:

r <<= 2;

is equivalent to

r = r << 2;

with the only difference r is evaluated only once.

And r << 2 is equivalent to (int) r << 2 as with the << the integer promotions are applied on each operand.

So we actually have:

r <<= 2;

equivalent to

r = 0x100;

This assignment is also not undefined behavior. 0x100 is converted to signed char prior to the assignment and this conversion is ruled by c99, 6.3.1.3p3 which says the conversion here is implementation defined.

Now if it was undefined behavior the "implementor may augment the language by providing a definition of the officially undefined behavior" (from c99 Rationale document) (this is stated in c99, 4.p6).

Upvotes: 2

P.P
P.P

Reputation: 121417

It's undefined behaviour in the sense that ISO C says so. If an implementation defines a specific behaviour for something (which is undefined in ISO C) then it's perfectly valid to do so. It's just not ISO C conformant one.

GCC has some extensions which are undefined in ISO C but valid in GNU C. E.g. Taking the size of a function/void (sizoof (a_function) and sizeof(void)).

The primary reason to follow ISO C is to make the code more portable. So if a behaviour is undefined for X (in ISO C) and your implementation defines a valid behaviour for X then your code is not portable other implementation(s) may not have anything defined for X.

Upvotes: 1

Sneftel
Sneftel

Reputation: 41522

From the C standard:

A conforming hosted implementation shall accept any strictly conforming program... A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any strictly conforming program.

In other words, the implementation is free to guarantee a particular behavior for what would otherwise be undefined behavior. It just can't do it in a way which changes defined behavior.

Upvotes: 2

Related Questions