What does !x mean, i understand !(x>30) means x can't be greater than 30 but this '!x' is just confusing me | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What does !x mean, i understand !(x>30) means x can't be greater than 30 but this '!x' is just confusing me

the not operator(!)

27th Oct 2016, 6:34 AM
Kai
Kai - avatar
2 Answers
+ 8
It's used for negating booleans and integers. For booleans: TRUE becomes FALSE and FALSE becomes TRUE. For integers: 0 becomes 1 and any non-zero value becomes 0.) For example; int x = 100; if(x) { return; } // evaluates TRUE if(!x) { return; } // evaluates FALSE, will not return (100 becomes 0) int x = 0; if(x) { return; } // evaluates FALSE, will not return if(!x) { return; } // evaluates TRUE (0 becomes 1) bool b = true; if(b) { return; } // true if(!b) { return; } // false bool b = false; if(b) { return; } // false if(!b) { return; } // true It also works when assigning new values. int x = 100; int y = !x; // 0 int z = !y; // 1 int q = !!x; // 1 int k = !(60<30); // 1 Pay attention to what happened to Q. The NOT is applied twice, so the first NOT (0) becomes NOT'ed again to 1. You may see this in some cases but it's nothing special.
27th Oct 2016, 7:33 AM
Neen
Neen - avatar
0
Basically the if statement checks if the value of a given condition is zero or non zero. Code: if(x) cout<<"and"; "abc" will only be printed if the value of x is anything except 0, i.e. abc will be printed for x = 6 as well as x = -5, but not for x =0 In a similar way, if the code is: if(!x) cout<<"xyz<<; "xyz" will only be printed for x = 0, and won't be printed for x =7 or x= -10 What !x (not x) does is that it changes the non zero value to a zero value and vice versa
30th Oct 2016, 3:16 PM
Subhabrata Ghosh
Subhabrata Ghosh - avatar