Using Exclamation Marks '!' in C

守給你的承諾、 提交于 2019-11-29 13:16:26

问题


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 named number - int number = 0;

I then use a while function involving an exclamation mark and number

while(!number)
{
    ...
}

I am confused with this because I do not know what does !number mean and what would be possible returned results? I am not sure if this can be used, but as I said, I saw it in my book.

Therefore, it would be great if someone could tell me what does !number mean and what does it evaluate?

Thank you in advance.


回答1:


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));



回答2:


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.




回答3:


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




回答4:


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




回答5:


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()



来源:https://stackoverflow.com/questions/22855483/using-exclamation-marks-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!