I realize that many programmers parenthesize the first operand of the conditional operator just to make the conditional expression easier to read, but is there any situation where parenthesizing it or not parenthesizing it would make a functional difference? I haven’t been able to come up with any.
expr1 ? expr2 : expr3 vs. (expr1) ? expr2 : expr3
>Solution :
#include <stdio.h>
int main () {
int a;
int b;
int c;
a = 1;
b = 0;
c = a = b ? 42 : 4242;
printf("a = %-8d b = %-8d c = %-8d\n", a, b, c);
a = 1;
b = 0;
c = (a = b) ? 42 : 4242;
printf("a = %-8d b = %-8d c = %-8d\n", a, b, c);
return 0;
}
Output:
a = 4242 b = 0 c = 4242
a = 0 b = 0 c = 4242
But I guess nobody would write code like that (at least I hope so).
Edit
To show the difference without and with parentheses the code below is simpler and equivalent:
// c = a = b ? 42 : 4242;
a = b ? 42 : 4242;
c = a;
// c = (a = b) ? 42 : 4242;
a = b;
c = a ? 42 : 4242;
Below is another example. In this case both a and c end up having different values.
#include <stdio.h>
int main () {
int a;
int b;
int c;
a = 1;
b = 1;
c = a -= b ? 42 : 4242;
printf("a = %-8d b = %-8d c = %-8d\n", a, b, c);
a = 1;
b = 1;
c = (a -= b) ? 42 : 4242;
printf("a = %-8d b = %-8d c = %-8d\n", a, b, c);
return 0;
}
Output:
a = -41 b = 1 c = -41
a = 0 b = 1 c = 4242