Why gcc will optimise an if statement but not a question mark operator?

时间:2017-12-18 07:19:17

标签: c++ gcc optimization

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, ie it generates effectively *dest = *dest, which is redundant. What's the reasoning for this and is there a way to improve it?

Thanks.

0 个答案:

没有答案