LittleBug
LittleBug

Reputation: 21

What does scanf("%d %d", &a, &b) == 2 mean?

In the below program, what does the code scanf("%d %d", &a, &b)==2 do?

The program gets two numbers and print the sum :)

#include <stdio.h>

int main(void)
{
    int a, b;
    while (scanf("%d %d", &a, &b) == 2)
        printf("%d\n", a+b);
    return 0;
}

Upvotes: 1

Views: 31917

Answers (5)

Anand Padole
Anand Padole

Reputation: 1

Scanf() returns an integer value and that value is nothing but the number of inputs accepted by scanf() function.

scanf("%d %d", &a, &b) will return 2 and now our statement becomes

while(2 == 2)
{
    // block of code
}

i.e 2==2 is true and it means:

while(1)
{
    // block of code executed
}

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

From the CC Standard

Returns
3 The scanf function returns the value of the macro EOF if an input failure occurs before
the first conversion (if any) has completed. **Otherwise, the scanf function returns the
number of input items** assigned, which can be fewer than provided for, or even zero, in
the event of an early matching failure

So the condition in the while loop checks whether exactly two items (numbers) were entered by the user.

while (scanf("%d %d", &a, &b)==2)

Upvotes: 0

Mikołaj Podbielski
Mikołaj Podbielski

Reputation: 56

Function scanf scans input according to format specifier provided as first argument. %d is format specifier for decimal integer so use %d %d if you want to match two numbers separated by space.

Other arguments are pointers where matched numbers should be written.

Function 'scanf' returns number of succesfully matched items. The 'while' loop is repeated as long as there were two matched numbers in user-provided input.

Upvotes: 4

HgMs
HgMs

Reputation: 282

scanf returns the number of items of the argument list successfully filled on success.
In this program, it means if the input is success, the result will be printed and it enters the next loop.
refer to scanf

Upvotes: 4

erenon
erenon

Reputation: 19118

From the documentation:

(scanf) Return value: Number of receiving arguments successfully assigned, or EOF if read failure occurs before the first receiving argument was assigned.

Which means, the statement in question means: while scanf successfully read two integer arguments.

Upvotes: 1

Related Questions