Jump to content



Photo

Why is a prefix operator better in C++ loops

c++ loops

  • Please log in to reply
3 replies to this topic

#1 SekaiStory

SekaiStory

    Neowinian

  • Joined: 19-June 09

Posted 27 November 2012 - 14:44

I come from a C# background and learning C++ in school. Our programming teacher has us to do iterations with a prefix like this:

for(int i = 0; i < 10; ++i) {}

Teacher says this is way better than using a postfix (with i++) and only makes a difference in C++ loops. He never explained why and I'd love to know.

Anyone can explain me why ++i is better than i++ in C++ loops?




#2 Lord Method Man

Lord Method Man

    Neowinian Senior

  • Tech Issues Solved: 1
  • Joined: 18-September 12
  • OS: Windows 8.1 Pro
  • Phone: Nokia Lumia 1520

Posted 27 November 2012 - 14:46

Odd, I've never been told this before. I don't see what the difference would be other than you are now iterating from 1-10 instead of 0-9 which just requires you to implement an additional step when looping through an array.

#3 ZakO

ZakO

    Neowinian

  • Tech Issues Solved: 2
  • Joined: 21-September 07
  • Location: Finland

Posted 27 November 2012 - 15:06

The post-increment operator (i++) may use a temporary variable, the pre-increment operator (++i) won't. However, in a lot of cases a good compiler will optimize the temporary variable away.

Discussion: http://stackoverflow...en-i-and-i-in-c - http://stackoverflow...en-i-and-i-in-c

#4 Lord Method Man

Lord Method Man

    Neowinian Senior

  • Tech Issues Solved: 1
  • Joined: 18-September 12
  • OS: Windows 8.1 Pro
  • Phone: Nokia Lumia 1520

Posted 27 November 2012 - 15:10

Interesting, I've never heard that before though it makes sense that a temp variable would be used. I'm not so hardcore about optimization that I'd worry about it though.