Using Exclamation Marks '!' in C

前端 未结 5 2064
情歌与酒
情歌与酒 2020-12-05 15:15

I have come across a problem involving exclamation marks and integers whilst reading a code in my reference book.

Let us say I have declared an integer variable name

相关标签:
5条回答
  • 2020-12-05 15:50

    The negation operator (!) simply just reverses the meaning of its operand.

    The operand or the expression must be of arithmetic or pointer type. But the operand/result of expression is implicitly converted to data type bool (boolean 0 means false, Non zero means True).

    The result is true if the converted operand is false; the result is false if the converted operand is true. The result is of type bool.

    so

    while(!number)
    {
        ...
    }
    

    since variable number is 0 , while(!number) ie, !0 which is 'negation of 0' which is 'TRUE' then it code enters the while loop()

    0 讨论(0)
  • 2020-12-05 15:58

    We can treat ! as not. So if a number is non-zero (either positive or negative) it returns Zero. If it is zero, it returns 1.

    int i = 13;
    printf("i = %d, !i = %d\n", i, !i);
    printf("!0 = %d\n", !(0));
    
    0 讨论(0)
  • 2020-12-05 16:02

    In C, !number will evaluate to 1 if number == 0 and to 0 if number != 0. And in C, 1 is true and 0 is false.

    Using an explicit comparison like number == 0 have the same effect but you might find it easier to read.

    0 讨论(0)
  • 2020-12-05 16:04

    It's a negation or "not" operator. In practice !number means "true if number == 0, false otherwise." Google "unary operators" to learn more.

    0 讨论(0)
  • 2020-12-05 16:07

    It is used for Negation of a number.It is a Unary Operator.

    For Example:-

    If we are using it with zero :- !0 then it will become 1

    with one !1 = 0

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