0
#include <stdio.h>

int main()
{
    int arr[3],i=0;
    while(i<3)
    {
        arr[i]= ++i;
    }
    for(int i=0;i<3;i++)
    {
        printf("%d\n",arr[i]);
    }
    return 0;
}

why is this outputting garbage value,1,2 ? i expected it to be 1,2,3. Please help

TIA

Heatblast
  • 55
  • 6
  • Give `arr` initial values – Ed Heal May 22 '21 at 12:12
  • @EdHeal and why? the problem is in the use of index and assignment variables. – Sourav Ghosh May 22 '21 at 12:13
  • Because without them yo do not know those initial values. Could be anything – Ed Heal May 22 '21 at 12:14
  • @EdHeal Right, but point here is, there should not be read-before-write scenario here. The increment in value creates the problem wit left out index `0`, – Sourav Ghosh May 22 '21 at 12:16
  • In `arr[i] = ++i;` which values do you expect to use as index? Do you expect `0,1,2`? – Gerhardh May 22 '21 at 12:18
  • You should use `arr[i] = i++;` – risingStark May 22 '21 at 12:20
  • 1
    Because this is undefined behaviour in C, as mentioned above. To order of evaluation of the assignment operator is not specified. In the while loop you want to do `arr[i] = i + 1; ++i;` to get the behaviour you want. – K D May 22 '21 at 12:24
  • @DK: It is imprecise to say the order of evaluation fo the assignment operator is not specified. The value computations of its operands are sequenced before the value computation of its result (C 2018 6.5 1), and the update of the left operand is sequenced after the value computations of the left and right operands (6.5.16 3). Any side effects in the operands are unsequenced. – Eric Postpischil May 22 '21 at 12:42

1 Answers1

0

The expression:

 arr[i]= ++i;

is undefined behaviour because i appears on both sides of the assignment operator (=), but the behaviour in this instance is empirically:

i++ ;
arr[i] ;

i.e. i is incremented before arr is indexed.

You need:

arr[i] = i + 1 ;
i++;

for the "expected" output:

1
2
3
Clifford
  • 88,407
  • 13
  • 85
  • 165