Why does gcc optimize the if statement, but not the question mark operator?

With the following code compiled with -O3,

extern int*  source;
extern int*  dest;

int main(int argc, char **argv)
{
    // dest conditionally written
    if (*source)
    {
        *dest = *source;
    }

    // dest always written?
    *dest = *source ? *source : *dest;
}

gcc generates code that writes to dest in A when *source != 0, but it generates code that always writes to dest for B, even when *source == 0, that is, it effectively generates *dest = *destwhich is redundant. What are the reasons for this and is there a way to improve it?

Thank.

+4
source share

Source: https://habr.com/ru/post/1690949/


All Articles