Search code examples
ccomma-operator

What does comma operator in C do when we return an integer with two values?


I was actually returning a float value when I typed , instead of . but it did not give me any error. Then I tried running the below code.

#include<stdio.h>
#include<conio.h>
int getValue();
int main()
{
    int a = getValue();
    printf("%d", a);
    return 0;
}

int getValue()
{
    return 2, 3;
}

Now the output is 3, that is it returned the second value. This happened two years ago and was searching for the proper answer since then.

Studying answers to this question I came to know that it returns the second value after evaluating, but what does it do with the first one?

I studied the logic of the stack(how the values are pushed and pop internally) but I don't think this have anything to do with it.

Does it processes the two values or do something else?


Solution

  • Quoting C11 standard, chapter §6.5.17, Comma operator

    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.

    Now, to answer your question

    what does it do with the first one?

    we can say, the first operand (left hand operand) is evaluated and the result is discarded.

    NOTE: I mentioned the result, not the effect.

    Just to clarify, in your case, you won't notice the effect, but you can notice it's effect if both the left and right hand expressions are related to the same variable. For example, let's discuss a simple exmple

    return p=3, p+2;
    

    We can break down the return statement like

    • asign a value 3 to the variable p [left hand side operator of ,]
    • execute p+2, ehich generates a value of 5. [right hand side operator of ,]
    • return the value 5 as the value of second argument [following the clause : "the result (of , operator) has its (evaluation of right-operand) type and value."]

    See a live demo.