954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

++ increment operator

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] ) ;
}
Aman6o
Newbie Poster
13 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

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] ) ;
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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.

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

Well explained, thanks.

Aman6o
Newbie Poster
13 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

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!

beingjoyful
Newbie Poster
1 post since Sep 2011
Reputation Points: 10
Solved Threads: 0
 
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 .

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You