Liste des Groupes | Revenir à cl c |
Em 8/2/2024 4:21 PM, James Kuyper escreveu:It is interesting to compare constexpr with the existing constant expression in C that works with integers.Compilers extend to work with unsigned long long.On 8/2/24 14:48, Keith Thompson wrote:I am doing experiments with constexpr. What happens with overflow in compile time? The answer is not so clear. Sometimes it does not compile and sometimes it works as in runtime.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.
When David was expressing the opinion Bart is talking about above, he
was talking about whether it was desirable for unsigned overflow to have
undefined behavior, not about the fact that, in C, it does have
undefined behavior. He argued that signed overflow almost always is the
result of a logical error, and the typical behavior when it does
overflow, is seldom the desired way of handling those cases. Also, he
pointed out that making it undefined behavior enables some convenient
optimizations.
>
For instance, the expression (num*2)/2 always has the same value as
'num' itself, except when the multiplication overflows. If overflow has
undefined behavior, the cases where it does overflow can be ignored,
permitting (num*2)/2 to be optimized to simply num.
>
constexpr int i = 1073741823;
constexpr int i2 = i*3/3; /*does not compile*/
But this compiles and outputs
#include <stdio.h>
int main()
{
constexpr signed char i = -2;
constexpr unsigned long long u = 0ull+i;
printf("%ull", u); /*prints 4294967294*/
}
Les messages affichés proviennent d'usenet.