Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

++nc vs nc = nc + 1

In K&R Ch 1:

The statement ++nc presents a new operator, ++, which means increment by one. You could instead write nc = nc + 1, but ++nc is more concise and often more efficient.

When would pre-increment be more efficient than the alternative? For most things, at least, the assembly for both is the add (edit: or inc) instruction. When do they differ?

like image 347
mwlow Avatar asked Dec 03 '22 05:12

mwlow


2 Answers

That text is long out dated. It might have been true in the 70's that compilers would produce more efficient output for ++n, but not any more. All modern compilers will produce identical code.

like image 133
David Heffernan Avatar answered Dec 18 '22 12:12

David Heffernan


For most things, at least, the assembly for both is the add instruction.

That's not quite true: there is often a separate "increment by one" instruction. However, that's irrelevant since any half-decent compiler will produce identical machine code for ++nc and nc = nc + 1.

In other words, there is no performance difference. There may have been when the book was written and compilers were not very good, but there isn't anymore.

like image 39
NPE Avatar answered Dec 18 '22 13:12

NPE