db2791
db2791

Reputation: 1110

Why does this program run the way it does?

#include<stdio.h>
int main()
{
    int a[5] = {5, 1, 15, 20, 25};
    int x, y, z;
    x = ++a[1];
    y = a[1]++;
    z = a[x++];
    printf("%d, %d, %d", x, y, z);
    return 0;
 }

"x" is printed as 3, but I would have expected it to return 2? In fact if I remove the "++" and set x equal to a[1], it returns as 2. It adds 1 to any value that is actually there. Am I missing something?

Upvotes: 1

Views: 48

Answers (4)

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

x=++a[1]; //  Now x got the value 2. 

In this line,

z = a[x++]; // x++ will be happen after the assigning of a[2] to z. So the value of x is incremented. So the x value is became 3. 

It is post increment so the z got the value as 15. Refer this link.

Upvotes: 0

Arun A S
Arun A S

Reputation: 7006

The ++ is called an increment operator. It increases the value by 1. In you code you have

x = ++a[1];

++ before a variable is the Pre Increment Operator. It increments the value of a[1] before assigning it to x. So the value of a[1] and x becomes 3.

The other one

y = a[1]++;

++ after the variable is the Post Increment Operator. It assigns a[1] ( which has already become 3 ) to y and then increments the value of a[1] to 4.

This link will help you

http://www.c4learn.com/c-programming/c-increment-operator/#A_Pre_Increment_Operator

Upvotes: 0

Vijay
Vijay

Reputation: 67221

x = ++a[1];//Increment a[1] and then assign it to x
y = a[1]++;//assign a[1] to y and then increment a[1]
z = a[x++];//assign a[2] to z and then increment x

Upvotes: 0

Gopi
Gopi

Reputation: 19864

"x" is printed as 3, but I would have expected it to return 2?

 x = ++a[1]; 

Here x = 2 because of pre-increment

The you have

z = a[x++];

x ++ = x + 1 = 2+1 = 3

Hence x=3

Upvotes: 4

Related Questions