On executing this piece of C command, the output of num is 7. I was expecting it to be 6, can anyone explain why and how it turns out to be 7?
#include <stdio.h>
int main() {
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int i = 0, num = 0;
num = a[++i + a[++i]] + a[++i];
printf("%d ", i);
printf("%d ", num);
return 0;
}
This is a bit tricky, the expression : a[++i+a[++i]]
, involves the increment of the variable i
two times, and comes out to be a[i + 2 + a[i + 2]]
, which is a[0 + 2 + a[2]] = a[4] = 4
, and the second operand, a[++i]
becomes a[3]
, which is equal to 3, hence, the final answer is 7. In other words, this is undefined behaviour.