Does sscanf("123456789123456789123456789", "%d", &n) have defined behavior?
CScanfUndefined BehaviorC Problem Overview
When sscanf()
or another function from the scanf
family is given a sequence of digits whose converted value exceeds the maximum value of the target integer type,
-
should the conversion be considered to have failed?
-
is the behavior defined at all?
C Solutions
Solution 1 - C
From the standard, 7.21.6.2p10 ((f)scanf
, applies to the whole family):
> … If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
Looks like another reason to be very cautious with the scanf
family. The strtoXX
functions have a fully defined behaviour. They return LONG_MAX
etc. for too large input and set errno == ERANGE
. So if you need exact information, tokenise the input manually and use these functions for conversion. Another benefit: better error handling.