Why is there a difference in the operation of the comma operator in the codes below?

Consider the following code snippets of Option 1:

int main() { int a; a=printf("hello"),printf("joke"); printf("%d",a); return 0; } 

Case 2:

 int main() { int a; a=(printf("hello"),printf("joke")); printf("%d",a); return 0; } 

Question 3:

 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 cannot understand the reason that when I use paranthesis in case 2, I get output as hellojoke4, and without using parantheis I get output as hellojoke5.

According to the output, when I tried to use the ternary operator, the same expression when executed using paranthesis or without using paranthesis returns the last output value of the printf expression, which is hellojoke4, so how the whole behavior is different in the case of the triple operator. And how the presence of paranthesis affects the operation of the comma, whether it acts as a delimiter or as an operator

+5
source share
1 answer

It's all about the low priority of the comma operator. Without parentheses, the expression is grouped as

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

So, assigning a from the first printf, and then the second printf . In the second example, the result of the second printf 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 
+9
source

Source: https://habr.com/ru/post/1214052/


All Articles