5

I am learning C from a book and I am starting with loop instructions. But there is a sample code which I could not understand.

Can anyone tell me why author has used status = scanf("%ld", &num); ? Why there is a = with scanf ?

/* summing.c -- sums integers entered interactively */
#include <stdio.h>
int main(void)
{
    long num;
    long sum = 0L; /* initialize sum to zero */
    int status;      
    printf("Please enter an integer to be summed ");
    printf("(q to quit): ");
    status = scanf("%ld", &num);
    while (status == 1) /* == means "is equal to" */
    {
        sum = sum + num;
        printf("Please enter next integer (q to quit): ");
        status = scanf("%ld", &num);
    }
    printf("Those integers sum to %ld.\n", sum);
    return 0;
}

3 Answers 3

6

Because scanf() returns a value indicating how well the string matched the format passed, i.e. how many parameters were successfuly filled with data.

You would know that if your read some kind of manual page, or the standard, if you ever encounter a function that you don't know, always read about it as much as you can, so you can understand how to use it.

5

scanf returns the number of successfully matched items from its specifier list. So, if you enter "q", scanf will return 0 (since "q" is not an integer), and the loop will terminate.

5

Please have a look at the man page of scanf(). It returns the number of items successfully scanned. So the return value is used to check the successfulness of scanf().

In your code,

 status = scanf("%ld", &num);
 // code
 while (status == 1) 

the return value of scanf() is stored into status and checked later to check whether scanf() has successfully scanned 1 item or not.

  • If it has returned 1, meaning a long int has been entered. Then the while() loop will continue, asking for the next input.
  • One you enter q, it won't match the coversion specifier %ld, hence scanf() will fail, hence it will return 0. Then the while() loop will terminate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.