NOT(~) vs NEGATION(!)

前端 未结 4 1451
無奈伤痛
無奈伤痛 2020-12-13 18:58
#include 

using namespace std;
int main(int argc, char *argv[]) 
{
   int i=-5;
   while(~(i))
   {
      cout<         


        
4条回答
  •  独厮守ぢ
    2020-12-13 19:56

    You are correct about i == -1 being the exit condition: your loop is equivalent to

    int i=-5;
    while(i != -1)
    {
        cout<

    When written this way, it should be clear why -1 is not printed the value is first printed, and only then incremented, that's why -2 is the last value that you print.

    The ! operator, on the other hand, will produce 1 only when it is given a zero. That's why the loop would print -1 when the ! operator is used in the loop condition.

提交回复
热议问题