5 ms·
Why not int add(int a, int b) { unsigned res = (unsigned) a + (unsigned) b; return (int) res; }
by deanmen 4y ago
Why not
int add(int a, int b) {
unsigned res = (unsigned) a + (unsigned) b;
return (int) res;
}
- torstenvl 4y ago"When a value with integer type is converted to another integer type ... [if] the new type is signed and the value cannot be represented in it; the result is implementation-defined." C99, 6.3.1.3. "When a value with integer type is converted to another integer type ... [if] the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised." C23 Draft, 6.3.1.3. Calling add(2147483647, 2147483647) with your code could trap, not from the overflow (which is well-defined for unsigned integers) but from casting 4294967294 to a signed integer. I also don't know if it would work with one's complement.