-1

For the testing code as follow:

#include <stdio.h>
int addTen(int x, int b[])
{
  b[2] =  x + b[2];
  return b[2];
}
void main(void)
{
   int a[3] = {4,5,6};
   int i = 2;
   printf("%i %i %i \n", a[i], addTen(10,a), a[i]);
}

Why is the output is 16, 16, 6? I know that even if the compiler processes the order from right to left like a[i] <- addTen(10,a) <-a[i]. After calling addTen(10,a), a[i] is already 16 (not 6). So why the output is not 16, 16,16? THANKS!

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
yvetterowe
  • 1,239
  • 7
  • 20
  • 34
  • 2
    Presumably because this compiler, at this phase of the moon, evaluates the arguments from right to left as you describe, so `a[i]` is 6 when it evaluates the last one, and 16 when it evaluates the second. But of course this is undefined behaviour, so there isn't an answer. – Mike Seymour Nov 11 '13 at 17:43
  • `main` needs to return `int`. – Shafik Yaghmour Nov 11 '13 at 17:46

2 Answers2

4

It's undefined behavior, you should read about sequence points. You're modifying a and simultaneously reading it in a same expression.

In addition the order of evaluating is not defined.

Community
  • 1
  • 1
masoud
  • 55,379
  • 16
  • 141
  • 208
4

There's no order defined for evaluating arguments. The compiler is free to evaluate arguments in any order, and will normally choose the most convenient order. So, you can't define any expected output.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70