'Why do I get an out of bounds error on an array inside a while loop even after using the decrement operator?

In the C++ code below, I got an out of bounds error on the last line.

int n;cin>>n;
int a[n];
for(int i=0;i<n;i++)
   cin>>a[i];
while(n--)
   {a[n]-a[n-1];}

There shouldn't be an issue since in the while loop, n will first get decremented and then it will start executing the code in the loop.

I have run it on multiple IDEs and it ran fine, but gave me an out of bounds error when I tried to submit the solution on codeforces.



Solution 1:[1]

n-- returns n prior to the decrement.

Thus, the last iteration has n == 0, meaning a[n - 1] accesses element -1, a clear case of undefined-behavior due to out-of-bounds array-access.

Changing to --n would give the adjusted variable instead, and thus "fix" the code.

As an aside, variable-length-arrays are not a standard C++ feature, though many C++ compilers accept it as an extension imported from C99.

Solution 2:[2]

The problem is with n--. Yes, it decrements n, but it evaluates to the value of n before the decrement. I.e., by the time n-- evaluates to 0 to break the loop, the loop already ran with n equal to 0. This causes a[n-1] to be out of bounds.

A very simple change will make it work, though: use --n. This evaluates to the value of n after the decrement, as so will break the loop as soon as n becomes 0.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Etienne de Martel
Solution 2 Ken Wayne VanderLinde