Reputation: 41
Moin Moin,
Currently I'm learning c++ and have an interesting effect which I can't explain to myself.
Why does *iterator++;
also work in this situation?
From my point of view it should increase the value to the pointer of. Does this mean that the ++
operator of the returned object from std::begin(feld)
is overridden to handle this to make it comfortable? I'm confused
void CArrayExamples::beginAndEndMethod()
{
int feld[] = { 0,1,2,3,4,5,6,7,8,9 };
int* iterator = std::begin(feld);
int* ending = std::end(feld);
while (iterator != ending)
{
std::cout << "iterator:" << iterator << std::endl;
std::cout << "*iterator:" << *iterator << std::endl;
std::cout << "ending:" << ending << std::endl;
std::cout << "*ending:" << *ending << std::endl;
std::cout << "-----------------------------------------------" << std::endl;
//why does this both work? :D
//*iterator++;
iterator++;
//TODO: Ask somebody!
}
}
Upvotes: 3
Views: 71
Reputation: 11977
The increment operator ++
has higher precedence than the indirection operator *
, so *iterator++
is interpreted as *(iterator++)
, i.e. increment the iterator/pointer and return the value pointed to by the old value.
Your code does not use the returned value, though.
If you want to increment the value, not the iterator/pointer, write (*iterator)++
.
Upvotes: 1