In C language, Why does n++
execute faster than n=n+1
?
(int n=...; n++;)
(int n=...; n=n+1;)
Our instructor asked
Modern compilers should be able to recognize both forms as equivalent and convert them to the format that works best on your target platform. There is one exception to this rule: variable accesses that have side effects. For example, if n
is some memory-mapped hardware register, reading from it and writing to it may do more than just transferring a data value (reading might clear an interrupt, for instance). You would use the volatile
keyword to let the compiler know that it needs to be careful about optimizing accesses to n
, and in that case the compiler might generate different code from n++
(increment operation) and n = n + 1
(read, add, and store operations). However for normal variables, the compiler should optimize both forms to the same thing.