C++ Programming - References - Discussion

Discussion Forum : References - Programs (Q.No. 2)
2.
Which of the following statement is correct about the program given below?
#include<iostream.h> 
int main()
{
    int x = 80; 
    int &y = x;
    x++;
    cout << x << " " << --y;
    return 0;
}
The program will print the output 80 80.
The program will print the output 81 80.
The program will print the output 81 81.
It will result in a compile time error.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
17 comments Page 2 of 2.

Sush said:   9 years ago
If there is no associativity involved then A, B options could be right. How can they choose only one?

Radu said:   9 years ago
There are several exceptions to this rule (Ex: For the &&, ||, and, operators) which are noted below.

Radu said:   9 years ago
There is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression "f1() + f2() + f3()" is parsed as "(f1() + f2()) + f3()" due to left-to-right associativity of operator+, but the function call to f3() may be evaluated first, last, or between f1() or f2() at run time.

The same stands for operator << used in this question.

Radu said:   9 years ago
First 2 comments (@Sharath and @Ilango) are incorrect.

The associativity of operator "<<" is "left to right" regardless if it's overloaded (like in case of ostream) or not, but that is not related to the evaluation of the scalar value x/y which is undefined (as @Demented_Hedgehog correctly said).

Demented_hedgehog said:   10 years ago
There's no sequence point for the << operator so the order of evaluation is unspecified.

Ilango said:   1 decade ago
&y=x // in this y becomes another name or like a pet name for x.

The --y represents a per-decrement its function is to decrement the value of the variable immediately when declared.

Hence the incremented value x=81 gets decremented by --y since x and y are same.

cout<<x<<" "<<--y // the 'cout' statement prints the values from right to left thus the answer is 80 80.

Sharath said:   1 decade ago
&y means alias of x , so here now x & y are same.

Then cout execution start right to left, So first x++ is 81 then --y is 80
output is 80 80


Post your comments here:

Your comments will be displayed after verification.