Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does “~scanf” mean?

Tags:

c

I saw it in a code like this

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

I know that scanf() has return value,but I can’t understand what does ~ mean

like image 202
Moon Avatar asked Jun 26 '26 11:06

Moon


1 Answers

This is a silly trick that relies on EOF having all its bits set. Since the standard does not guarantee the exact value of EOF, the behavior of this program is platform-dependent.

When scanf detects end-of-input, it returns EOF. Standard requires EOF to be negative. Very often EOF is set to -1. When ~ is applied to -1, you get back a zero, so the loop stops. On platforms with EOF defined as some other negative number the loop will never stop. Code's behavior also depends on the implementation-defined behavior of ~ with signed values.

You should rewrite the loop as follows:

while (scanf("%d", &a) != EOF) {
    ...
}
like image 193
Sergey Kalinichenko Avatar answered Jun 28 '26 00:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!