nobalG
nobalG

Reputation: 4620

Incrementing arrays in C,SPECIAL CASE

I am confused by the following code:

#include <stdio.h>

int main()
{
    int a[] = {5, 15, 1, 20, 25};
    int i, j, m;

    i = ++a[1];   /*statement 1*/
    j = a[1]++;   /*statement 2*/
    m = a[i++];   /*statement 3*/

    printf("\n%d\n%d\n%d\n", i, j, m);

    return 0;
}

Statements 1, 2, 3 are a bit confusing for me; I don't not get the way these are producing the output for me. Can anyone shed some light on this please?

Upvotes: 1

Views: 2649

Answers (4)

Anish
Anish

Reputation: 2917

The First Statement

i = ++a[1] ---> Increments the value of a[1] (i.e) i value will be 16

Second Statement

j = a[1]++ ---> Assign the value of a[1] to j and then incremented(i.e) j would be 16.

Third Statement

m = a[i++] --> Assigning value of a[i] to m and i is incremented.

Upvotes: 0

Poonam Bhatt
Poonam Bhatt

Reputation: 10302

i = ++a[1];   /*statement 1*/

Hear a[1] will be 15. and Pre Increment operator will increase a[1] with 1 S0 i will be 16

j = a[1]++;   /*statement 2*/

Post increment operator will also increment the value of a[1] by 1. so j will be 16.

m = a[i++];   /*statement 3*/

Here, it is i++, so post increment oprator will increase i by 1..earlier i was computed 16 . now i will now be 17.

So a[17] has no value. so m will be junk value

Upvotes: 2

Aif
Aif

Reputation: 11220

In case of doubt, what you can do is use gdb:

  1. Compile your code setting debug flag (-g for gcc) gcc -g -o so stackoverflow.c
  2. run gdb gdb ./so
  3. identify lines to break list in gdb
  4. set breakpoints break 6 (first break is line 6)
  5. Step forward step
  6. Display values print i or print a[1] for instance.

But beware, if you call print ++a[1] in gdb you may change your program behaviour!

Upvotes: 0

Gaurav
Gaurav

Reputation: 28755

i=++a[1];   /*statement 1*/   // increments the value of a[1] and assigns to i
j=a[1]++;   /*statement 2*/   // assign the value of a[i] and then increments the value of a[i] to j
m=a[i++];   /*statement 3*/   //  assign a[i] to m, and increment i


i=++a[1];   // a[1] is 15 here so i =16, and a[1] =16
j=a[1]++;   // a[1] is 16 so j =16 and a[1] =17
m=a[i++];   // i is 16 here but index 16 does not exists here, so program fails

Upvotes: 3

Related Questions