3 ms·
Dividing by zero is undefined behaviour. It's fairly straightforward to provide a proof, given a definition of division by zero, that 1 = 0. It's often done in
by bregma 5y ago
Dividing by zero is undefined behaviour.
It's fairly straightforward to provide a proof, given a definition of division by zero, that 1 = 0. It's often done in first-year introduction to algebra classes.
It would be correct, then for a compiler to substitute the value 1 everywhere the programmer used the value 0 (or NULL, or '\0') and still produce a valid program with the same behaviour because 1 and 0 have been proven to be equivalent.
So no, you are not right in thinking all implementations must define undefined behaviour. Undefined is undefined. C code containing undefined behaviour is not valid C code and the compiler to only required to produce correct output when the input is valid C code.
- mannykannot 5y agoThat is a fair point about divide-by-zero [1], but the very post I was replying to gave an example of where this compiler does say explicitly what happens in one case of what falls under undefined behavior in the C standards. To clarify, what I am interested in here is the interaction of C-standard UB with any guarantee this compiler may give with regard to semantics preservation under optimization. [1] In reality, the hardware will do something, and deterministically in every case that I am aware of, when the divide operation is invoked with zero as the divisor. Computer division is not an exact implementation of mathematical division.
- bregma 5y ago> To clarify, what I am interested in here is the interaction of C-standard UB with any guarantee this compiler may give with regard to semantics preservation under optimization. To clarify my point: undefined behaviour has any semantics you might want it to have. Anything and everything is semantically correct even under optimization. Even if the compiler says it will do one thing and then does another: it's correct either way. The computer may "do something" with division by zero. Or the compiler might completely elide the code and replace it with a picture of a teapot before it even gets as far as hitting a register in anger. It's still valid, semantically, because you're dividing by zero from which you can prove anything and everything.
- a1369209993 5y ago> It's fairly straightforward to provide a proof, given a definition of division by zero, that 1 = 0. No, it is not. It's fairly straightforward to provide a proof, given the false[0] premise that x*y/y = x, that 1 = 0. 0: Hell, I don't even need division by zero for that one: uint8_t x = 2; x = x*128; // x is now (uint8_t)(2<<7) == (uint8_t)256 == 0 x = x/128; // x is now 0>>7 == 0 // x is now x*y/y is 2*y/y is 2 if(x == 2) printf("it's two\n"); printf("it's %i\n",(int)x);