Take the 2-minute tour ×

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;
   cout << "The Number You Entered Was " << x << "!" << endl;
   return 0;
share|improve this question
and then what?? –  Vijay Aug 28 '12 at 5:21

3 Answers 3

up vote 2 down vote accepted

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

cin >> num;

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 x is declared without an initializer, which means that it begins its life uninitialized (with indeterminate value). Later you put some specific value into x by reading it from cin, but this is no longer initialization (in C++ meaning of the term).

It might be a good idea to declare your x with some determinate initial value, like

int x = 0;

although personally I'm not a big fan of "dummy" initializers.

share|improve this answer
but aren't you reading in a string? –  Derp Aug 28 '12 at 5:19
@Derp: String? What string? Where did "string" come from? –  AndreyT Aug 28 '12 at 5:20
I just figured that you would be reading in a string, even though it is a number. Like if the user would type "one". Anyway I'm getting uninitialized local variable x? –  Derp Aug 28 '12 at 5:22
@Derp std::cins operator<<` has many overloads, one of those takes an integer. See my answer. –  juanchopanza Aug 28 '12 at 5:22
cin >> num is equivalent cin.operator>>(int& num). As you can see, the type there is int, not a string. –  sudarkoff Aug 28 '12 at 5:22

You should drop the static_cast.

cin >> num;

std::cin's operator>> has overloads that take integral types.

Note that you are not initializing a variable through a function at all. You are assigning a value to a variable by passing a reference to it to a function.

share|improve this answer

No need for the static_cast stuff. Your function is given a reference to an int, and you want to read an int. Since you've passed a reference to the variable, the changes to it in your input function will be reflected in the caller.

share|improve this answer

Your Answer


