-1

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189

4 Answers4

2

i is incremented 3 times within the same expression in num = a[++i + a[++i]] + a[++i];

This has undefined behavior in C. It is a moot point trying to explain why it outputs 7 or 6 or anything whatsoever. Undefined behavior can be anything.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

llvm on OS X gives me 6 and a warning:

wi.c:5:8: warning: multiple unsequenced modifications to 'i' [-Wunsequenced]

which suggests that we are looking at an undefined behavior. The exact nature of what it undefined here is not clear to me thus far, but feels a bit irrelevant.

MK.
  • 33,605
  • 18
  • 74
  • 111
  • [This SO answer](http://stackoverflow.com/a/19862240/4045754) explains and provides links for why this is undefined behavior and should be avoided. – yeniv Feb 17 '17 at 04:31
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.

Jarvis
  • 8,494
  • 3
  • 27
  • 58
-1
i = 0;
num = a[ ++i + a[++i]] + a[++i]

Will evaluate to

num = a[1+ a[2]] + a[3]
num = a[1 + 2] + a[3]
num = a[3] + a[3]
num = 3 + 3
num = 6
Anshuman
  • 758
  • 7
  • 23