Is a += b more efficient than a = a + b in C?

前端 未结 7 1727
耶瑟儿~
耶瑟儿~ 2020-12-10 04:42

I know in some languages the following:

a += b

is more efficient than:

a = a + b

because it removes the n

相关标签:
7条回答
  • 2020-12-10 05:16

    In the simple cases shown in the question, there is no significant difference. Where the assignment operator scores is when you have an expression such as:

    s[i]->m[j1].k = s[i]->m[jl].k + 23;   // Was that a typo?
    

    vs:

    s[i]->m[j1].k += 23;
    

    Two benefits - and I'm not counting less typing. There's no question about whether there was a typo when the first and second expressions differ; and the compiler doesn't evaluate the complex expression twice. The chances are that won't make much difference these days (optimizing compilers are a lot better than they used to be), but you could have still more complex expressions (evaluating a function defined in another translation unit, for example, as part of the subscripting) where the compiler may not be able to avoid evaluating the expression twice:

    s[i]->m[somefunc(j1)].k = s[i]->m[somefunc(j1)].k + 23;
    
    s[i]->m[somefunc(j1)].k += 23;
    

    Also, you can write (if you're brave):

    s[i++]->m[j1++].k += 23;
    

    But you cannot write:

    s[i++]->m[j1++].k = s[i]->m[j1].k + 23;
    s[i]->m[j1].k = s[i++]->m[j1++].k + 23;
    

    (or any other permutation) because the order of evaluation is not defined.

    0 讨论(0)
提交回复
热议问题