+16

Which is more efficient n=n+1 or n++?

Whats the major difference between these statements as both of them do the same operations.

c++ c

11/9/2019 7:09:47 AM

toma_hawk

52 Answers

New Answer

+22

The second has two characters less.

+11

Most compilers optimizes the code you write, and those two will generate the same assembly code. In that case, it would be more efficient to just write n++ or ++n than n=n+1.

+10

When incrementing an integer value n++ is more efficient if you only add one to a variable But n=n+1 is more efficient if you add a value that is greater than 1 (e.g. n=n+4, n=n+5) PS: it would be more efficient if the language you are using has this: n += 4, n+= 5

+10

toma_hawk On theory basis n+=1 is more efficient than n++ as n+=1 does not generate a temporary, where as n++ does generate a temporary. But modern compilers can do wonders and n++ could be more efficient as their is nothing blocking in it. With n+=1 the next n+=1 cannot be completed till first n+=1 is complete, so it is sort of blocking. With single operation it is difficult to tell.

+8

Modern compilers generate the same assembly code hence practically its no difference, since its just an INC instruction.

+4

Both are same.... in terms of efficiency as both statements can be considered as having constant time complexity...

+2

both are the same but n++ is easy to write

+2

They are the same but you should be careful about pre and post increment

+2

With: n++ ; You write less code and I think it's more intelligent way of code. 👊👊

+2

n++ is more efficient bcoz there is least time to load, compile & output.

+2

n++

+2

According to 'c' and 'c++' pre and post decrement or increment operator is good because it feels handy with program Many languages does not support 'n++' type of format like python..,we have to take care about them🙂

+2

n++ Better then the other

+2

As it takes less space

+2

Since the compiler selects the most efficient route of execution, the n=n+1 would be automatically converted to n++. There is no real difference between these as far as the compiler is concerned.

+2

N=N+1 is efficient

+1

You could also compare them with n+=1

+1

both are same but n++ is better

+1

n++ is most usefull and easy

+1

n++