Commas after a scanf statement?

93 views Asked by At

Not my code, but from here. In the read_data() function there is a scanf with something after it I haven't see before. What does it do? Is it STL?

scanf("%d %d\n", &a, &b), G[a].pb(b), deg[b]++;
2

There are 2 answers

0
templatetypedef On

This is a use of the comma operator. The comma operator, which is used fairly uncommonly, sequences together a bunch of expressions together as a single expression. In this case, the statement

scanf("%d %d\n", &a, &b), G[a].pb(b), deg[b]++;

means "do the scanf, then call pb(b) on G[a], then call deg[b]++, evaluating to the result of deg[b]++.

I see that it's used in this context:

for(i = 1; i <= M; i++)
    scanf("%d %d\n", &a, &b), G[a].pb(b), deg[b]++;

Honestly, this strikes me as poor style. It would be better to write this:

for(i = 1; i <= M; i++) {
    scanf("%d %d\n", &a, &b); 
    G[a].pb(b);
    deg[b]++;
}

The above code is functionally equivalent and a lot more readable - you don't have to post to Stack Overflow or know weird details of the C++ language to figure out what it means. :-)

0
P.P On

It's just multiple expressions made into a single statement by using comma operator. It helps to avoid the braces around the for loop (which is not a good idea in my opinion as it obfuscates the code).

It's functionally equivalent to:

   for(i = 1; i <= M; i++) {
        scanf("%d %d\n", &a, &b);
        G[a].push_back(b); /* after macro expansion */
        deg[b]++;
   }