i ++ and ++ i

Tram Ho

I remember in an interview at the company, with a test code in the loop, so for what I also spend ++i . The boss wondered 2 or 3 times why he didn’t use i++ but I kept saying “it’s faster but I forgot the reason”. Fortunately, the boss did not seem to know the answer, so he let himself pass 😂. But until now, I couldn’t remember the cause so far, so I came back and asked gugo-sama right away and wrote this article.

Difference

This basic difference applies to most languages ​​and compilers today.

++i increases the value of i by 1 and returns the new value.
i++ is similar but the return value is the initial value of i before being incremented by 1.

One point worth noting here, not to be confused, is that i++ will return the value i allowed to assign before it is incremented. Assignments always last, so that’s not possible.

In essence, the program will create a temporary variable (temp) to store the initial value of i and return that value to allow assignment after i++ operation is done.

Performance

Although it takes effort to create a temp variable for i++ , in fact the difference in performance is not large. Almost all modern compilers will optimize that operation. The proof is in the example of this on stackoverflow, gcc to compile the results are the same for two code files contain spending loop ++i and i++ .

But in C++ , the discrepancy can be significant in some cases. Specifically, with the user-defined type, ie the class you create, because operator++() is a function and the compiler does not know how to optimize the creation of the temp object in it. How does it know what you define and how big it will be in the class?

So which one to use within for ?

As for me, ++i has become an unwritten convention. No matter which project I use, I don’t care about performance for the brain. Many gurus in the coder world give advice:

In any case, follow the guideline “prefer ++ i over i ++” and you won’t go wrong

(from many Anonymous)

A bit of side effect and undefined behavior

Example 1:

Example 2:

I will not explain what is “Side effect or UB?” Here. This topic is also quite interesting, so I will write a separate article about it. But through the two examples above, you can also see their danger, if the first assignment in example 2 and in the loop, then 😨.

See you in the following articles! 2

Share the news now

Source : Techtalk