the execution gave a segmentation fault. But when I changed to i>0, it was fine. Does TIdx restrict the numbers to >=0?
This is a simple programming error. Please make yourself comfortable with the way a for loop works.
As long as the condition (i>=0) is true, the iteration expression --i and the body C[i]=555 will be executed. So when i==0, there will be another iteration and the next value will be --0 which is most likely out of the array.
No, this is not the case. The loop would be executed one last time (as intended) for i==0 and for i==-1 the condition would be false and the loop would not execute the loop body again.
However, I guess TIdx is an unsigned type, so --iis not -1, but the biggest possible positive number for this type, which is always bigger or same as zero. So basically you wrote an infinite loop, which crashes while accessing C[0xFFF...FFF] :wink:
You are right, I misinterpreted the loop. The effect is the same: out-of-bounds access ;-)
To complete this problem, the loop could look like this
for (TIdx i(numElements-1); i<numElements; --i)
C[i]=555;
With this we "exploit" the underflow as the condition becomes false after the underflow happened. However this of course works only if TIdx is unsigned! Otherwise you will get the error Benjamin described. So having both checks can make sense:
for (TIdx i(numElements-1); i>=0 && i<numElements; --i)
C[i]=555;
hoping that the compiler sees that one of the both conditions will never be false. A last solution could be
for (TIdx i(numElements-1); i+1>0; --i)
C[i]=555;
but I don't know whether the compiler is smart enough to not add one in every loop iteration...
For me the last one is the most beatiful, but decide yourself. If on doubt choose the fastest one. :wink:
To add another version:
for (TIdx i(numElements); i>0; --i)
C[i-1]=555;
I realized that TIdx cannot be negative. So I solved it like this.
for (TIdx i(numElements); i>0; --i)
{
TIdx ii(i-1);
C[ii]=555;
}
^^
that's ok as long as ii is const, so the compiler is more likely to optimize it out ;)
TIdx const ii(i-1);
C[ii]=555;
Thanks for all the answers!
Most helpful comment
To add another version: