0

just today I stumbled across this short piece of code that confused me a little.

#include <iostream>
#include <iterator>

int main()
{
 int array[] = {0,1,2,3,4,5,6,7,8,9};

 auto start = std::begin(array);



 while (start != std::end(array))
 std::cout << *start++ << std::endl;
}

The thing that is confusing me here is that the 0 is the first output. I read a lot of posts regarding the order of the 2 operators and every single one said: "start" would be incremented first, THEN dereferenced. But std::begin() returns an iterator to the beginning of the array. With this being said, if I increment the pointer to the beginning of the array first before dereferencing it, shouldn't my first output be the 1? Thanks in advance!

Philipp317
  • 11
  • 3

1 Answers1

0

*start++ uses the post increment operator. With post increment the item is incremented but the value returned is the value before incrementing. You are dereferencing that value so that is why the output starts at 0.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • I know that the post-increment operator increments the value after "using" it, but I got confused here because of the operator-precedence stating that any incrementing would be done before dereferencing. Isn't that a contradiction? – Philipp317 Jan 22 '16 at 14:21
  • @Philipp317 Nope. The increment happened first it is just the `*` uses the return value from `start++` and not what `start` is after the `++` happens. – NathanOliver Jan 22 '16 at 14:24
  • Thanks a lot, that cleared things up. :) – Philipp317 Jan 23 '16 at 19:13