Search code examples
coperator-keyword

What does a ! operator mean in front of a variable?


I have just a simple question, I'm learning C programming and I know that the ! operator means logical NOT. My question is that what does it mean in this case in a do while cycle as a condition? Is it checking somehow if the variable is changed?

I know I should probably find it somehow, but when I try to google '!'s it doesn't want to show what I meant.

#include <stdio.h>

int main() {
    int input, ok=0;
    do {
        scanf("%d", &input);
        if ( /* condition */) {
            //the input is wrong it will scan another one
        }
        else {
            //the input is correct, so the while cycle can stop
            //we don't need more inputs
            ok = 1;
        }
    } while (!ok);

    //...
    //...
    //...

    return 0;
}

Solution

  • !ok is the same as ok == 0.

    Remember that in C, any non-zero scalar value in a Boolean context means "true" while zero means "false". It's a common C idiom to write !foo instead of foo == 0. It works for pointers as well:

    FILE *foo = fopen( "some_file", "r" );
    if ( !foo )
    {
      fprintf( stderr, "could not open some_file\n" );
      return EXIT_FAILURE; 
    }
    

    So, while ( x ) is the same as while ( x != 0 ), and while ( !x ) is the same as while ( x == 0 ).