Using the return value of "scanf ()" to check the end of the file

I searched the net on how to use the scanf return value to check the end of the file! I found the following code. But I hardly understand?

How does this method work?

What does the '~' operator mean?

while(~scanf("%d",&n)) { /* Your solution */ } 
+4
source share
3 answers

This is a terrible way to check if a value is different from -1. ~x returns the bitwise negation of x . Therefore, bearing in mind the free code used for negative numbers (for most compilers , by the way, so this approach is not even very portable) -1 is represented by the sequence 1-s and, therefore, ~(-1) will produce a zero value.

Please do not use this approach. Just write scanf("%d", &n) != EOF The way is easier to understand.

+9
source

~ is a bitwise NOT operator. So this is a slightly confusing way of looping until scanf returns a value other than -1. In other words,

 while(~scanf("%d",&n)) 

equivalently

 while(scanf("%d",&n) != -1) 
+2
source

In C ~, an operator that performs a bit-muddy shift operation complements the original number. And in C there is no boolean type, 0 is false, everything else is true, in your example:

 while(~scanf("%d",&n)) { /* Your solution */ } 

scanf () returns EOF if there are no more characters to read, which is -1 (not on all platforms!), so -1 is represented (111 ... 32 times in a 32-bit architecture) ~ EOF = 0 in this way risk that code does not work for all platforms.

0
source

All Articles