Browsing articles tagged with " operator++"

Prefix vs. Postfix Increment and Decrement Operators in C++

Mar 23, 2012   //   by Ray Mitchell   //   Blog  //  2 Comments

Here is how most programmers new to C-based languages are taught to write for a loop:

for (int i = 0; i < someValue; i++) {
    // Do something
}

Unfortunately this starts programmers off on the wrong foot by teaching them the bad habit of using i++ (postfix increment) as the default way to increment a value.  Using ++i (prefix increment) would work just as well since the result of the increment expression is not used by the containing expression (the for loop).  Here is the equivalent code using ++i1:

for (int i = 0; i < someValue; ++i) {
    // Do something
}

It’s preferable to use prefix increment when the result of the increment is not used by the containing expression.  To see why, let’s first take a look at what the compiler generates when it encounters i++ and ++i.
Read more >>

Recent Posts