0

code snippet:

#include <stdio.h>
int computeSum(int number1, int number2) {
    int sum;
    sum = number1 + number2;
    return sum;

}
int main()
{
      int sum = 0,k=0;

      k,sum= computeSum(4,2);
      printf("%d %d",sum,k);

     return 0;
}

What is the functionality of comma ( , ) between k and sum,why it doesn't evoke any error?what is its significance?

  • It's just syntactically wrong. What are you trying to achieve? – Denis Sablukov Jan 13 '19 at 11:48
  • @DenisSablukov Why do you think it is wrong? I'd think it's just the comma operator separating two expressions. The left expression is just the `k`, the right one is the assignment (only) to sum. (In particular, nothing is assigned to `k`). – Peter - Reinstate Monica Jan 13 '19 at 11:50
  • @DenisSablukov "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." (from the n1570 draft, 6.5.17) – Peter - Reinstate Monica Jan 13 '19 at 11:54
  • @PeterA.Schneider my bad. Didn't know that.. – Denis Sablukov Jan 13 '19 at 11:54

3 Answers3

2

k,sum= computeSum(4,2); just get the value of k then assign sum

perhaps you wanted to do k = sum = computeSum(4,2); ?

an assignment is an expression returning a value, not a statement like an if ...

bruno
  • 32,150
  • 7
  • 23
  • 37
2

Precisely stated, the meaning of the comma operator in the general expression

e1 , e2

is evaluate the subexpression e1, then evaluate e2; the value of the expression is the value of e2.

When compiling your program with gcc compiler, it gives warning message:

warning: left-hand operand of comma expression has no effect
k,sum= computeSum(4,2);
^

Reason is, the expression

k,sum= computeSum(4,2);

is evaluate the subexpression k and then sum= computeSum(4,2);. The subexpression k result is unused.

H.S.
  • 10,799
  • 2
  • 12
  • 26
2

The one comma-operator you use, between the expression k and the assignment-expression, just makes a single expression out of two expressions, and orders them.

Of course, the first expression has no effect, thus the compiler warns you (if you ask for it):

prog.c: In function 'main':
prog.c:12:8: warning: left-hand operand of comma expression has no effect [-Wunused-value]
   12 |       k,sum= computeSum(4,2);
      |        ^
Deduplicator
  • 43,322
  • 6
  • 62
  • 109