Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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?

like image 850
glglgl Avatar asked Feb 24 '26 13:02

glglgl


2 Answers

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.

like image 181
Sneftel Avatar answered Feb 26 '26 03:02

Sneftel


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).

like image 27
ouah Avatar answered Feb 26 '26 04:02

ouah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!