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.

Karthikeyan 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 i.e:4

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

Isha said:   3 years ago
As per my knowledge the coding part is;

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

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?

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.

Souvik said:   1 decade ago
The output will vary compiler to compiler,because i++means,i=i+1;
so when u r assign i=i++ then ambiguity may come, so depending upon the compiler o/p changes.

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.

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?

MAG said:   6 years ago
On running the same code in code blocks, it is giving 3 as a output, because it is a post-processor.

Please, someone, explain the correct answer.

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.


Post your comments here:

Your comments will be displayed after verification.