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 3 of 7.

Amolak said:   1 decade ago
@Siraj.

Output will be : 3, 4.

Krishanu said:   1 decade ago
Please run that code the out will be 3.

Sneha naik said:   1 decade ago
@Suraj.

Answers will be 4, 3 in post increment value will be assigned later incremented so j=3 and i=4.

Saurabh said:   1 decade ago
For that question some compiler will give different answer like Dev C++.

Is giving 3 instead of 4 because when a single expression causes the same object to be modified then inspected the behavior is undefined. In this case I = i++;

Here variable I is being modified and then it is being used by the compiler. That's why answer 4 is coming here.

Mohammad Mohsin said:   10 years ago
Answer must be 3, because post increment operator assigns value first and then incremented.

In DEV CPP while I run above program answer is 3.

Akanksha said:   10 years ago
Can anyone solve my doubt? What is the output of this?

i = i++ + i++;
printf("%d",i);

Juber said:   10 years ago
int i = 3;
i = 3+3;
i = 6;
i++;
i = 7;
i++;
i = 8;

Finally i = 8 will be print;

Sweety said:   9 years ago
Answer will be 3, not 4. Just compile it on another online compiler. And conceptually also it should be 3.

Karthik said:   9 years ago
I tired this;

#include<stdio.h>
int main()
{
int i=3;
i = i++;
printf("%d\n%d", i,i++);
return 0;
}

______________
The output is
3
4

Can anyone explain how i++ became 3?

Karthik said:   9 years ago
I tried this code in code block and I got the output as 3. But here, the compiler says 4. Why?


Post your comments here:

Your comments will be displayed after verification.