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

53 views Asked by At

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;
}
1

There are 1 answers

3
Tom Karzes On BEST ANSWER

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.