C++ Programming - References - Discussion

Discussion Forum : References - Programs (Q.No. 6)
6.
Which of the following statement is correct about the program given below?
#include<iostream.h> 
int main()
{
    int x = 10, y = 20;
    int *ptr = &x;
    int &ref = y;

    *ptr++;
     ref++;    

    cout<< x << " " << y;
    return 0; 
}
The program will print the output 10 20.
The program will print the output 10 21.
The program will print the output 11 20.
The program will print the output 11 21.
It will result in a compile time error.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
11 comments Page 1 of 2.

Aishwarya said:   4 years ago
Because the priority is to the increment:
*ptr++; // == *(ptr++);
So it's the value if the POINTER wich is incremented, not the value of 'x'.

But if you write this :
(*ptr)++; // The value of 'x'is incremented.
(3)

Sangeetha said:   7 years ago
Anyone can give the clean explanation, about in which case cout will start from right to left?
(1)

A student said:   7 years ago
Here *ptr holds the value of x means *ptr =10.
*Ptr++ =11.
But it doesn't change the value of x.
But &ref=y (is alias) means ref=y.
So ref++ means y++.
So the output is the value of x is 10.
And y is 21.

Hoang Pham said:   8 years ago
The key is the precedence of the two operators, postfix ++ and indirection *

++ has a higher precedence than *.This mean *p++ is going to be grouped as: *(p++).

Pawar Manisha said:   8 years ago
How? Explain its output.

Manisha said:   8 years ago
Hello, anyone please help me to get this.
(1)

Sherin said:   10 years ago
How it come 10 20?
(1)

Ilango said:   1 decade ago
If we can perform arithmetic operation on pointers then why we can't increment the value of the pointer. Please anyone explain this.

Swapnil said:   1 decade ago
How it happens ?

SomebodY said:   1 decade ago
++ operator have associativity L to R.


Post your comments here:

Your comments will be displayed after verification.