Why is there a variation in the working of the comma operator?

c, comma-operator

Solution

It is all down to the low precedence of the comma operator. Without parentheses, the expression is grouped as

(a=printf("hello")), printf("joke");

So, an assignment to `a` from the first printf, followed by the second `printf`. In the second example, the result of the second `printf` is assigned to `a`.

To simplify:

a = 1, 2;   // (a = 1), 2; post-condition a==1
a = (1, 2); // a = (1, 2); is equivalent to a = 2; post-condition a==2

Problem

Consider the following code snippets Case1: ``` int main() { int a; a=printf("hello"),printf("joke"); printf("%d",a); return 0; } ``` Case2: ``` int main() { int a; a=(printf("hello"),printf("joke")); printf("%d",a); return 0; } ``` Case3: ``` int main() { int a; a=10>8?(printf("hello"),printf("joke")):printf("hello"); printf("%d",a); return 0; } ``` Case4: ``` int main() { int a; a=10>8?printf("hello"),printf("joke"):printf("hello"); printf("%d",a); return 0; } ``` I am unable to catch out the reason that when I use parenthesis in case 2,then I get the output as hellojoke4,while without using pantheists I get the output as hellojoke5. As per the output it is when I tried using ternary operator ,then the same expression when executed using parenthesis or without using parenthesis,returns the last output value of printf statement that is hellojoke4 ,so how does altogether the behaviour differs in the case of ternary operator. And how does the presence of parenthesis affects the working of the comma ,does it act like a separator or as an operator

Original source