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

Why can't I use pointers with a ternary operator?

Task: int’s and pointers to them are given. Using only pointers, find the variable with the minimum value among the variables and assign the minimum to the maximum.
Question: Why does the code below output "the value required as the left assignment operand"
*p_a < *p_b ? *p_b = *p_a : *p_a = *p_b;

#include <stdio.h>

int main() { 
    int a = 5, b = 7;
    int * p_a = &a, *p_b = &b;
    *p_a < *p_b ? *p_b = *p_a : *p_a = *p_b;
    printf("%d %d", *p_a, *p_b);
    return 0;
}

I tried to enter a flag that will take on the minimum number, but it also didn’t work
Example of a flag

#include <stdio.h>

int main() { 
    int a = 5, b = 7;
    int * p_a = &a, *p_b = &b;
    int l; //flag
    *p_a < *p_b ? l = *p_a : l = *p_b;
    printf("%d", l);
    return 0;
}

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

>Solution :

You just need to add parentheses to group the assignments. For example:

int main() { 
    int a = 5, b = 7;
    int * p_a = &a, *p_b = &b;
    *p_a < *p_b ? (*p_b = *p_a) : (*p_a = *p_b);
    printf("%d %d", *p_a, *p_b);
    return 0;
}

and

int main() { 
    int a = 5, b = 7;
    int * p_a = &a, *p_b = &b;
    int l; //flag
    *p_a < *p_b ? (l = *p_a) : (l = *p_b);
    printf("%d", l);
    return 0;
}

It is a bit strange to use ?: like this though. Normally you would use the ternary operator when you actually want to use its value. In a case like this, where you’re just performing assignments and not using the result value of the operator, you would normally use if/else.

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