In standard C, overflow is an exceptional condition and behaviour is then undefined per standard. From draft n1570 for C11, 6.5 Expressions § 5:
If an exceptional condition occurs during the evaluation of an expression (that is, if the
result is not mathematically defined or not in the range of representable values for its
type), the behavior is undefined.
That means that you cannot process overflow in a way that would be defined per standard. That being said, most compilers simply keep the low order bits of the result that can fit in the type representation and ignore the highest order bit(s). This is what MSVC, gcc, and clang do.
From now on, I will assume that your system uses the int32_t
(resp. int16_t
or int64_t
) for signed int and ignores overflow. It is not mandated per standard but is common enough and is probably what your system does.
There are 2 possible overflows in your code. First is the scanf
function: as said by @n.m., nothing is said for the behaviour of this family of function if the input sequence does not fit in the type. I will assume that the submitted number is acceptable as a signed int (between INT_MIN and INT_MAX). Anyway, it is trivial to have it detected by the user: just display x
: if it is not the just typed number, then an overflow occured.
Second is here:
y = (y * 10) + temp;
Here again it is easy to test for overflow, by doing the reverse operations and controling that all was fine:
int next = (y * 10) + temp;
if ((next < 0) || (y != (next - temp) / 10)) {
// an overflow occured...
...
In theory, nothing can guarantee that negating a positive int is a valid negative int, but this is true for the intXX_t
types, so that should be enough to detect an overflow in the reverse
function.