Sujet : Re: What is your opinion about unsigned int u = -2 ?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 02. Aug 2024, 19:48:38
Autres entêtes
Organisation : None to speak of
Message-ID : <87r0b6g3qx.fsf@nosuchdomain.example.com>
References : 1 2 3 4 5 6
User-Agent : Gnus/5.13 (Gnus v5.13)
Bart <
bc@freeuk.com> writes:
[...]
C23 assumes 2s complement. However overflow on signed integers will
still be considered UB: too many compilers depend on it.
>
But even if well-defined (eg. that UB was removed so that overflow
just wraps as it does with unsigned), some here, whose initials may or
may not be DB, consider such overflow Wrong and a bug in a program.
>
However they don't consider overflow of unsigned values wrong at all,
simply because C allows that behaviour.
>
But I don't get it. If my calculation gives the wrong results because
I've chosen a u32 type instead of u64, that's just as much a bug as
using i32 instead of i64.
There is a difference in that unsigned "overflow" might give
(consistent) results you didn't want, but signed overflow has undefined
behavior.
There are perhaps infinitely many ways to get wrong results. It doesn't
necessarily matter whether you get those wrong answers via code that has
well defined behavior or code that has unspecified or undefined
behavior.
The standard had to say *something* about the behavior of arithmetic
operations that yield results outside the range of the relevant type.
It happens to say that the behavior is undefined for signed integer
types and well defined for unsigned integer types. It is to a large
extent an arbitrary choice (though there are historical reasons for it),
but it means that programmers are free to take advantage of things like
`-1u`. It also means they can be bitten by that behavior if they're not
careful.
Incidentally, what the standard says is that unsigned operations do not
overflow at all. It could equivalently have said that they do overflow
and the behavior of overflow is well defined.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */