首页 > 解决方案 > Output prediction cannot understand the while statement

问题描述

I'm looking for the expalanation of this problem. I cannot understand the while part and why does it print 6.

#include <stdio.h>
#include<stdlib.h>

int main() 
{
    int array[] = {1, 2, 4, 0, 4, 0, 3};
    int *p, sum = 0;

    p = &array[0];

    while (*p++)
        sum += *p;

    printf("%d\n", sum);
    return 0;
}

标签: cloopswhile-loopoutput

解决方案


这是您的 while 循环的更易读的形式:

while (*p != 0)
{
  p = p + 1;   // you can put "p++;" here, which has the same effect
  sum += *p;
}

现在你应该自己理解了。


推荐阅读