Reputation: 13
long long int a;
scanf("%lld",&a);
printf("n : %lld\n",a);
input is 9223372036854775808 (LLONG_MAX + 1)
but output is 9223372036854775807 (LLONG_MAX)
x64 GNU/Linux and I use GCC compiler
Upvotes: 1
Views: 141
Reputation: 320747
Overflow in scanf
triggers undefined behavior.
However, many popular implementations of scanf
use functions from strto...
group internally to convert strings into actual numbers. (Or, maybe more precisely, they use the same lower-level implementation primitives as strto...
functions.) strto...
functions generate max value of the target type on overflow. The side effect of that implementation is what you observe in your test. strtoll
was apparently used, which produces LLONG_MAX
on positive overflow.
But you should not rely on that, since the behavior is undefined.
Upvotes: 9
Reputation: 441
output will be unpredictable.
i have tried the same piece of code with simple int .
i have attached the output .
Upvotes: 0
Reputation: 1283
Because scanf
clamps input to valid ranges, but raises the ERANGE
error, as answered in this question and in the manpage:
The value
EOF
is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.EOF
is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
...
ERANGE
The result of an integer conversion would exceed the size that can be stored in the corresponding integer type.
Note this behaviour isn't required by the language or POSIX standards, but is evidently true for many standard library implementations (including yours).
Upvotes: 4
Reputation: 4041
It is an undefined behavior. In this if you assign that value to variable instead of getting from input, that time you will get the warning while compilation.
Upvotes: 1