I have been using ! (lo开发者_如何学Cgical 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?
int my_negate(int x)
{
return x == 0 ? 1 : 0;
}
!e
can be replaced by ((e)?0:1)
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.
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.
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.
精彩评论