Derp
Derp

Reputation: 929

Initializing Variable Through Function

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;
}

Upvotes: 1

Views: 121

Answers (3)

juanchopanza
juanchopanza

Reputation: 227418

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.

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320531

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.

Upvotes: 2

pb2q
pb2q

Reputation: 59617

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.

Upvotes: 0

Related Questions