6

My ma'am gave me one question to solve. To predict the output of the following code.

#include <stdio.h>
int main()
{
    int i = 0, j = 0;
    printf("Output is : ");
    while (i < 5, j < 10)    // Doubt: how does while accept 2 arguments?? and how it works??
    {
        i++;
        j++;
    }
    printf("%d, %d\n", i, j);
}

I thought it was a syntax error. But when I tried to run, it gave me output.

Output is : 10, 10

But How? Can anyone explain?

But if I remove the first printf statement printf("Output is : "); and run it, my antivirus give me a alert that a Trojan is detected. But how it becomes a Trojan?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Shreyash S Sarnayak
  • 2,309
  • 19
  • 23
  • 9
    see [How does the Comma Operator work](http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work) – quantdev Nov 25 '14 at 18:17
  • 1
    to explain you have to know how "," operator works. if you do x = m,n ; //it will take value of m if you do x= (m,n); // it will take the value of n because of parenthesis. – Nihar Nov 25 '14 at 18:27
  • 1
    "while(i<5,j<10)" means perform "i<5" and then perform "j<10". the overall result of expressions separated by the comma operator is the value of the right-most expression. so, the line becomes "while(j<10)". "i<5" is useless here. – skrtbhtngr Nov 25 '14 at 21:12
  • if I remove the `printf` statement and run it, my antivirus give me a alert that a `trojan` is detected. – Shreyash S Sarnayak Nov 26 '14 at 05:49
  • 3
    That's probably just flawed Antivirus heuristic, nothing relevant. – Matteo Italia Nov 26 '14 at 06:19
  • http://stackoverflow.com/a/1136117/3496666 – Kumar Nov 26 '14 at 07:25

1 Answers1

6

The comma operator is a binary operator and it evaluates its first operand and discards the result, it then evaluates the second operand and returns this value.

so in your case,

First it will increment i and j upto 5 and discard.
Second it will iterate i and i upto 10 and provide you the result as 10, 10.

you can confirm by using the following code,

while (i < 5, j < 10)    // Doubt: how does while accept 2 arguments?? and how it works??
{
    i++;
    j+ = 2;
}
Sridhar DD
  • 1,972
  • 1
  • 10
  • 17