2
#include<stdio.h>

int main(){
    int array[10] = {3,0,8,1,12,8,9,2,13,10};
    int x,y,z;
    x =++array[2];
    y =array[2]++;
    z =array[x++];
    printf("%d\t%d\t%d\n",x,y,z);
    return(0);
}

I guessed the output of this would be 9,9,1 or something(Actually Not sure)

But this broke out when compilied

10,9,10

PS:Forgive me, I am a noob

Mat
  • 202,337
  • 40
  • 393
  • 406
Omjelo
  • 109
  • 8
  • `x =++array[2]; array[x++];` The first increments `x` to make it `9`. Then the `x++` in the second statement affect `x` in the same way as `x=x+1` so makes it 10. – kaylum Apr 16 '20 at 07:29
  • 1
    This example is same as in [Pre increment vs Post increment in array](https://stackoverflow.com/q/16869020/5291015) – Inian Apr 16 '20 at 07:30

2 Answers2

2

Here are the values step by step:

int array[10] = {3,0,8,1,12,8,9,2,13,10};
int x,y,z;

x = ++array[2]; // array[2] becomes 9 before assignment to x
    // x:9  array[2]:9

y = array[2]++; // array[2] becomes 10 after assignment to y
    // x:9 y:9  array[2]:10

z = array[x++]; // z becomes array[x] (last element)
    // x:10 y:9 z:10
Danny_ds
  • 11,201
  • 1
  • 24
  • 46
1

Making a table is useful:

statement        x   y   z   array[2]
-------------------------------------
                 ?   ?   ?    8
x = ++array[2]   9   ?   ?    9
y = array[2]++   9   9   ?   10
z = array[x++]  10   9  10   10

By the way, I never use the value of pre- and post-increment operations in my own code. It makes the logic harder to understand. Here is a rewritten version without side-effects in expressions:

#include <stdio.h>

int main(void)
{
    int array[] = {3, 0, 8, 1, 12, 8, 9, 2, 13, 10};
    int x, y, z;

    array[2]++;
    x = array[2];
    y = array[2];
    array[2]++;
    z = array[x];
    x++;
    printf("%d\t%d\t%d\n", x, y, z);
    return 0;
}
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60