How does logical negation work in C?

前端 未结 5 915
春和景丽
春和景丽 2020-12-03 11:47

I have been using ! (logical negation) in C and in other languages, I am curious does anyone know how to make your own ! function? or have a creative way of making one?

相关标签:
5条回答
  • 2020-12-03 12:13

    !e can be replaced by ((e)?0:1)

    0 讨论(0)
  • 2020-12-03 12:22

    Remember the bang operator '!' or exclamation mark in english parlance, is built into the programming language as a means to negate.

    Consider this ternary operator example:

    (some condition) ? true : false;
    

    Now, if that was negated, the ternary operator would be this

    (some condition) ? false : true;
    

    The common area where that can get some programmers in a bit of a fit is the strcmp function, which returns 0 for the strings being the same, and 1 for two strings not the same:

    if (strcmp(foo, "foo")){
    
    }
    

    When really it should be:

    if (!strcmp(foo, "foo")){
    }
    

    In general when you negate, it is the opposite as shown in the ternary operator example...

    Hope this helps.

    0 讨论(0)
  • 2020-12-03 12:24

    If you want to overload an operator, the proper prototype is:

    bool operator!();
    

    I'm not a big fan of overloading operators, but some people like their syntactic sugar. EDIT: This is C++ only! Put it in the definition of your class.

    0 讨论(0)
  • 2020-12-03 12:36
    int my_negate(int x)
    {
        return x == 0 ? 1 : 0;
    }
    
    0 讨论(0)
  • 2020-12-03 12:40

    C considers all non-zero values "true" and zero "false". Logical negation is done by checking against zero. If the input is exactly zero, output a non-zero value; otherwise, output zero. In code, you can write this as (input == 0) ? 1 : 0 (or you can convert it into an if statement).

    When you ask how to "make your own ! method", do you mean you want to write a function that negates a logic value or do you want to define what the exclamation-point operator does? If the former, then the statement I posted above should suffice. If the latter, then I'm afraid this is something that can't be done in C. C++ supports operator overloading, and if doing this is a strict necessity then I would suggest looking there.

    0 讨论(0)
提交回复
热议问题