#include <iostream>
using namespace std;
int main()
{
int x = 7;
int* ptr = &x;
cout << *ptr << " ";
(*ptr)++;
cout << *ptr;
return 0;
}
Answer: 7 8
Explanation:
- In this C++ code, an integer variable
x
is declared and initialized with the value 7. - A pointer
ptr
is declared and initialized to store the address ofx
using the address-of operator (&
). cout << *ptr << " ";
prints the value pointed to byptr
, which is the value ofx
, i.e., 7. So, the first output is "7 ".(*ptr)++;
increments the value stored at the memory location pointed to byptr
. In this case, it increases the value ofx
from 7 to 8.cout << *ptr;
prints the updated value pointed to byptr
, which is now 8. So, the final output is "8".
This code demonstrates how a pointer can be used to access and modify the value of a variable indirectly.