add array elements with increment operators [duplicate]

Your program has unspecified behavior. In the expression a[top]+a[--top], the C and C++ language standards do not specify which of a[top] and a[--top] will be evaluated first, and they don’t specify when the -- operator is executed relative to other expressions. Compilers can evaluate this as they see fit. Yours is computing --top first, setting top to 0, and then is calculating a[0]+a[0], yielding 20.

Don’t use a variable twice in an expression in which you pre- or post- increment or decrement it.

Leave a Comment