Pre-increment and Post-increment

I guess it would be good to just mention, even not going into too much detail, that there is in fact a fundamental difference between ++i and i++.

++i : This is a pre-increment operator and it is used to increment the value of a variable before using it in an expression, the value is first incremented and then used inside the expression.

i++ : This is a post-increment operator and it is used to increment the value of the variable after executing the expression completely in which post-increment is used, the value is first used in an expression and then incremented.

An example for people that might be interested, you could do the while loop in one line (inside the while) like this:

int32 index = 0;
while (index < actors.Num())
{
	UE_LOG(LogTemp, Display, TEXT("Overlapping actor name: %s"), *actors[index++]->GetActorNameOrLabel());
}

and it would work just fine, because the index is 0 on the first loop and is immediately incremented to be 1 and used in the next loop. But this happens after the value is used in an expression.

And this would crash the engine with index out of bounds exception:

int32 index = 0;
while (index < actors.Num())
{
	UE_LOG(LogTemp, Display, TEXT("Overlapping actor name: %s"), *actors[++index]->GetActorNameOrLabel());
}

since the value is first incremented and is 1 in the first loop, meaning that we are trying to access the second element in an array that has only one element.

Interestingly enough, in for loop it doesn’t matter if we use ++i or i++, but it’s a more complicated matter :slight_smile:

4 Likes

Privacy & Terms