2 ms·
> all you have to do to avoid UB on signed integer overflow is check for overflow before doing the operation (and C23 finally adds features to do that for you).
by xigoi 4y ago
> all you have to do to avoid UB on signed integer overflow is check for overflow before doing the operation (and C23 finally adds features to do that for you).
…making your code practically unreadable, since you have to write ckd_add(ckd_add(ckd_mul(a,a),ckd_mul(ckd_mul(2,a),b)),ckd_mul(b,b)) instead of a * a + 2 * a * b + b * b.
- chongli 4y agoThat's not the correct syntax for the ckd_ operations. They take 3 operands, the first being a pointer to an integer where the result should be stored. And they return a bool, which you need to check in a conditional. If you're just going to throw out the bool and ignore the overflows, why bother with checked operations in the first place?
- xigoi 4y agoYeah, I realize that now. That's even worse. So you'll have to write something like int aa,twoa,twoab,bb,aaplustwoab,aaplustwoabplusbb; if (ckd_mul(a,a,&aa)) { return error; } if (ckd_mul(2,a,&twoa)) { return error; } // … if (ckd_add(aaplustwoab,bb,aaplustwoabplusbb)) { return error; } return aaplustwoabplusbb; So ergonomic! > If you're just going to throw out the bool and ignore the overflows, why bother with checked operations in the first place? I'd expect the functions to return the result on success and crash on failure. Or better, raise an exception, but C doesn't have exceptions…