This is a code snippet I created for learning purposes in C++, I am currently trying to teach myself. My question is:
Why does *ptr = 30 change the output values of the two last cout statements in my main? (the output is 30, 30, 30). Consequently, why does int y = 30; and ptr = &y; not change the output in my main, and stay local to the function? (if I comment out *ptr = 30, and not the former two statements, the output is 30, 5, 5)
If I change the function input to void printPointer(int *&fptr) -- and comment out only *ptr = 30 -- then *ptr in my main will be modified, but not x. I understand this, as the pass by reference is modifying the pointer, but not how my first statement modifies *ptr and x in my main.
#include <iostream>
using namespace std;
void printPointer(int *fptr);
int main()
{
int x = 5;
int *ptr = &x;
printPointer(ptr);
cout << *ptr << endl;
cout << x << endl;
return 0;
}
void printPointer(int *fptr)
{
// int y = 30; // this does not change the output of the last two couts in main, output = 30, 5, 5
// fptr = &y;
*fptr = 30; // uncommenting this and commenting out the former two statements: output = 30, 30, 30
cout << *fptr << endl;
}