I need help understanding the increment operator and the output of this program.
I am confused with the output of 'i' and 'm' According to me: i = 4 and m = 20 but, that is not what you get when you compile. Please explain. Thanks in advance.

#include <stdio.h>
main( )
{
    int a[5] = { 5, 3, 15, 20, 25 } ;
    int i, j, k = 1, m ;
    i = ++a[1] ;
    j = a[1]++ ;
    m = a[i++] ;
    printf ( "\n%d %d %d %d", i, j, m, a[1] ) ;
}

Edited 5 Years Ago by Narue: Added code tags

Break it down:

int a[5] = { 5, 3, 15, 20, 25 } ;
int i, j, k = 1, m ;
a[1] = a[1] + 1;
i = a[1] ;
j = a[1] ;
a[1] = a[1] + 1;
m = a[i] ;
i = i + 1;
printf ( "\n%d %d %d %d", i, j, m, a[1] ) ;

Look at line 6. Your incrementing a[1] which equals 3 by 1 so i = 4.
Look at line 8. Your incrementing i so that would make i = 5.

I need help understanding the increment operator and the output of this program.
I am confused with the output of 'i' and 'm' According to me: i = 4 and m = 20 but, that is not what you get when you compile. Please explain. Thanks in advance.

#include <stdio.h>
main( )
{
    int a[5] = { 5, 3, 15, 20, 25 } ;
    int i, j, k = 1, m ;
    i = ++a[1] ;
    j = a[1]++ ;
    m = a[i++] ;
    printf ( "\n%d %d %d %d", i, j, m, a[1] ) ;
}

why arent u initialising i or l, it may get garbage value!

why arent u initialising i or l, it may get garbage value!

Read the code more carefully. The first use of i assigns a value to it. There's also no l , so I assume you meant either j or m , both of which follow the same process as i .

This article has been dead for over six months. Start a new discussion instead.