Search code examples
c++scanftilde

What does ~(tilde) means before scanf function in c++?


I found a code that takes input string and print them out.

But I don't know what does the tilde means in front of the scanf.

I found tilde can be used for either destructor or binary negation but it doesn't look like both. And the code doesn't work without tilde.


int main() {
    char arr;

    while (~scanf("%c", &arr)){
        putchar(arr);
    }
}

Solution

  • I found tilde can be used for either destructor or binary negation but it doesn't look like both.

    It's the bitwise NOT operator applied to the return value of scanf() as you mentioned latter.

    And the code doesn't work without tilde.

    As @Mukul Gupta explained in their comment:

    scanf returns the number of values it scanned successfully or EOF if it reaches the end of file. EOF is a macro that represents a negative value. On most platforms, the value of EOF is (int) -1. In this case, taking 1's complement of -1, will make the value as 0 and is used to break from the loop.