! operator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>


bool checkSomething(){
    return false;
}

int main(){
    if(!checkSomething){
        std::cout << "hello" << std::endl;
    }
    
    return 0;
}


What does ! operator do? I thought it reverses false to true.
You're not actually calling the function.

Change the if statement to this

if(!checkSomething()) // add the ()

Edit : Check the Edit ^^
Last edited on
Well than it should print out 'hello' to the screen but it doesn't.

but if I change return false to return true, it works.


Edit: thanks it works, but how come compiler didn't give me an error? it's weird...
Last edited on
but how come compiler didn't give me an error? it's weird...
You are allowed to use the names of functions for use with function pointers, so it's still correct syntax, but using it in the if statement doesn't make sense. My compiler gives a warning about the address of function name always evaluating to true.
Last edited on
In your original code,

1
2
3
    if(!checkSomething){
        std::cout << "hello" << std::endl;
    }


A function name by itself, without the call operator ( the parenthesis ) is a pointer to the function. So checkSomething is a pointer to the function which will certainly be a non-zero address value for the pointer. An implicit conversion to boolean takes place and since non-zero values evaluate to true, the expression checkSomething evaluates to true. Adding the negate operator flips the value so !checkSomething now evaluates to false and the if statement body is skipped. It compiles because it is legal code. It just wasn't doing what you thought it was.
Topic archived. No new replies allowed.