C Programming - Expressions - Discussion

Discussion Forum : Expressions - Find Output of Program (Q.No. 9)
9.
What will be the output of the program?
#include<stdio.h>
int main()
{
    int i=3;
    i = i++;
    printf("%d\n", i);
    return 0;
}
3
4
5
6
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
70 comments Page 2 of 7.

Meghana said:   1 decade ago
@Anjena the answer will be:.

7 9 5 7 (evaluate from right to left).

Srini said:   1 decade ago
Step 1: int i=3
Step 2: i=i++ post increment so still i=3 in this statement
Step 3: after completion of the above statement i will be increment by 1 so i becomes 4
step 4: in printf statement i value is printed as 4

Arnab Sanyal (IIT, BOMBAY) said:   1 decade ago
i is initialised to 3. We know that every variable can hold one value at a time. So only after assigning 3, with post increment operator i is assigned to 4.

Edwin Jose said:   1 decade ago
In post increment i value get incremented in the next step only.

Govindaraju said:   1 decade ago
i=i++; => i =3;
After executing this statement the i value is i=i.

+1 => 4.

As it is post decrement operator the value will be changed after the execution of the statement.

Dixit said:   1 decade ago
First i = 3 will be assigned to i (i = i++).

Then i will be incremented to 4.

OmPrakash said:   1 decade ago
Has anyone compile the code? Do it and you will find '3' is the answer.

Avinash said:   1 decade ago
Answer = 4 is appropriate among the given options.

To say accurately the answer should be "undefined".

i=i++;// the behavoiur of this expresiion is undefined.

In an expression never use value of a variable if the value of the variable is getting changed..

Similarly,

i=i++*i++;//undefined b/c trying to modify twice with in an expression.

i=i*i++;//undefined.

Himanshu said:   1 decade ago
Actually precedence of post increment operator (++) is greater than = operator.

So, i=i++; first increment occurs and then assignment occurs.

Siraj said:   1 decade ago
#include<stdio.h>
int main()
{
int i=3,j;
j = i++;
printf("%d %d\n", i,j);
return 0;
}

What will be the output now?


Post your comments here:

Your comments will be displayed after verification.