C++ Programming - References - Discussion

Discussion Forum : References - Programs (Q.No. 8)
8.
Which of the following statement is correct about the program given below?
#include<iostream.h> 
int main()
{
    int m = 2, n = 6;
    int &x = m;
    int &y = n;
    m = x++; 
    x = m++;
    n = y++;
    y = n++;
    cout<< m << " " << n; 
    return 0; 
}
The program will print output 2 6.
The program will print output 3 7.
The program will print output 4 8.
The program will print output 5 9.
The program will print output 6 10.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
5 comments Page 1 of 1.

J.sireesha said:   4 years ago
Here the values of x and m would be the same like m and n.
m=2 and n=6.

One thing remember in the program we use post increment operator
So, the first the actual value is assigned to the left hand variable.

For example;
a=5
b=a++;

Then b value =5 because we use post-increment.
Like in the same way;
Given values:
m=2,n=6
x=&m,y=&n;

Then x=2,y=6;
m=x++;
Then m=2
x=m++;
Then x=2
n=y++;

Then n=6
Y=n++;

Then y=6
So the final values of m=2 and n=6,
So, the option A is correct.
(2)

Legndery said:   9 years ago
This is clearly wrong.

m = x++;

Increments x, then returns the previous x. and assigns it to m.

So, x=x+1, but returns the old x. So the old x is assigned to m.

x = m++;

Same logic:

n = y++;
y = n++;

Mohammad Mohsin seed said:   1 decade ago
Answers depend on compiler.

In DEV CPP it gives 2 6. While in turbo C++ it gives o/p 3 7.

Simicivan173 said:   1 decade ago
This answer is only partially correct. (Depends on compiler!).

The result could be 2 6.

Because for example:

int x = 0; //initialize.

x = x++; //make copy of old version of x, increment x.

//assign old to x (lhs).

cout<<x; //prints 0 (not 1).

Amisha said:   1 decade ago
Here x = m.

And y = n are same.

First the m = x++ means m = x = 3 then x = m++.

So again m is increment by one so value is x = m = 4;

Same as for n and y operator so y = n = 8.
(2)

Post your comments here:

Your comments will be displayed after verification.