Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In C, Is parenthesizing the first operand of the conditional operator ever actually required?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading