-2

Given the following code:

// this is a solution of uva 12279    
#include<stdio.h>

int main()
{
    int arr[10000],i,n,a,d=0,e=75;
    while(scanf("%d",&n),n)// what's that means?
    {
        d++;
        int c=0,b=0;

        if(n==0)
            return 0;

        for(i=0;i<n;i++)
            scanf("%d",&arr[i]);

        for(i=0;i<n;i++)//this is for loop
        {
            if(arr[i]==0)
                c++;
            else
                b++;
        }
        a=b-c;

       printf("Case %d: %d\n",d,a);
  }
  return 0;
}

What is the meaning of while(scanf("%d",&n),n)?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • possible duplicate of http://stackoverflow.com/questions/16240482/on-understanding-how-printfd-n-int-n-scanfd-n-nn-works – Smit Mar 07 '17 at 01:43
  • `while(scanf("%d",&n),n)` can also be an infinite loop when `scanf()` returns `EOF` and `n` is who-knows-what. It is poor code. – chux - Reinstate Monica Mar 07 '17 at 04:20

1 Answers1

6

In this condition

while(scanf("%d",&n),n)

there is used the so-called comma operator.

scanf("%d",&n),n

The value of the condition is the value of the second operand of the comma operator that is of the variable n. If n is not equal to 0 then the loop is executed.

You can imagine it the following way

start: scanf("%d",&n);
if ( n != 0 )
{
    //...
    goto start;
}

Thus within the body of the loop the variable n can not be equal to 0 unless it is reassigned. As result this statement from the presented code snippet

if(n==0)
return 0;

does not make sense.

It would be more correct to write the condition of the loop the following way

while ( scanf("%d",&n) == 1 && n != 0 )

From the C Standard (6.5.17 Comma operator)

2 The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335