Using ? : in C for the first time

I just started classes at my school in programming and I learned how to use ? : for the first time. My first question is what this is called, because my prof didn't say what it is called.

Second, I'm writing a program that prints even when given an even number and odd when given an odd number. I wanted to write it like this

int main() {
    int x = 3;
    char *string;

    if (x % 2 == 0 ? string = "Even" : string = "Odd");

    printf("%d is %s", x, string);
}

the problem is I get an error error: lvalue required as left operand of assignment at if (x % 2 == 0 ? string = "Even" : string = "Odd"); and it's the string = "Odd" part.

Am I not allowed to assign expressions to variables inside of if( ? : )? I want to keep my code short and not have to write it like

if (x % 2 == 0) {
    printf("%d is Even", x);
} else {
    printf("%d is Odd", x);
}


Read more here: https://stackoverflow.com/questions/68491288/using-in-c-for-the-first-time

Content Attribution

This content was originally published by codey at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: