I was searching the net on how to use return value of scanf to check the end of file! I found the following code.But i am having difficulty in understanding?
How is this method working?
What does the '~' operator signify?
while(~scanf("%d",&n)) {
/* Your solution */
}
This is a horrible way to check if a value is different from -1. ~x
returns the bitwise negation of x
. So having in mind the complimentary code used for negative numbers(on most compilers by the way so this approach is not even very portable) -1 is represented by a sequence of 1-s and thus ~(-1)
will produce a zero.
Please don't use this approach. Simply write scanf("%d", &n) != EOF
Way easier to understand.
~
is the bitwise NOT operator. This is therefore a slightly obfuscated way of looping until scanf
returns something other than -1. In other words,
while(~scanf("%d",&n))
is equivalent to
while(scanf("%d",&n) != -1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With