I’m learning pointers and references but I’m having trouble grasping the concept. I need to declare a variable in my main function and then have it initialized through a function by user input, without returning anything. I’ve tried:
#include <iostream>
using namespace std;
void input(int &num){
cout << "Enter A Number" << endl;
cin >> static_cast<int>(num);
}
int main(){
int x;
input(x);
cout << "The Number You Entered Was " << x << "!" << endl;
return 0;
}
You are doing it correctly, except for that
static_cast<int>there. What is it doing there? What made you use that cast?Get rid of that cast, and it should work. This
is all you need.
P.S. Just keep in mind that in C++ terminology the term initialize has very specific meaning. Formally, initialization is always a part of variable definition. Whatever changes you do to that variable after the definition is no longer initialization. In your case variable
xis declared without an initializer, which means that it begins its life uninitialized (with indeterminate value). Later you put some specific value intoxby reading it fromcin, but this is no longer initialization (in C++ meaning of the term).It might be a good idea to declare your
xwith some determinate initial value, likealthough personally I’m not a big fan of “dummy” initializers.