C++ Programming - References - Discussion

Discussion Forum : References - Programs (Q.No. 9)
9.
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 3 7.
The program will print output 4 8.
The program will print output 5 9.
The program will print output 6 10.
It will result in a compile time error.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
5 comments Page 1 of 1.

Vivek Roy said:   5 years ago
A reference variable is same as constant pointer and arithmetic operation(i.e x++ & y++) is not allowed.
(1)

Rakesh said:   1 decade ago
Hi friends I am little bit confuse taking this program.

When I run this program in Turbo then output is 3, 7;

When I run in GCC compiler then it display an error;

"int &p = m++";

When I write it as like.

Int &p = ++m;

This it works properly.

My question is how can I guess, in which compiler we have to run this program if it is not mention in Question.

AnonymousAvenger said:   1 decade ago
Because References cannot be bound to temporary objects.
In "int &p = m++"

Compiler stores the old m value in a temporary object and then increment value of temporary object and returns the temporary object

However this statement will work:

int &p = ++m;

Avio said:   1 decade ago
C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

Keshav Khetriwal said:   1 decade ago
Reference requires memory address not an ordinary integer value.

Post your comments here:

Your comments will be displayed after verification.