I'm trying to understand how references/pointers/dereferencing works in c++. Please see below for some example code :
#include <iostream>
#include <cstdio>
int& plusThree(int num)
{
int threeMore = num + 3;
//std::cout << "threeMore is " << threeMore << "\n";
//printf("threeMore is %d", threeMore);
return threeMore;
}
int main()
{
int three = plusThree(0);
std::cout << "three is " << three << "\n";
return 0;
}
The function plusThree() shouldn't work, and if you run the code, it doesn't. It'll return three is 0. However, if you uncomment either of the lines which prints threeMore, main will now print three is 3...
So my questions are as follows:
Why does the function
plusThree()not work? is it becauseint&means it should return an integer reference, butreturn threeMoreis returning an int?Why does the function
plusThree()now work, if one ofstd::coutorprintfis uncommented?
Thanks!