Use the links for a and b .
void getvals(int &a, int &b) { cout << "input value a "; cin >> a; cout << "input value b "; cin >> b; }
This declares getvals() to accept two control parameters. Modifying an object reference changes the object that was passed to the function call.
Without a reference, the parameter is passed by value, which creates a copy of the object passed to the function. Then the changes made to the parameter in the function affect only the copy.
Alternatively, you can use std::pair<int, int> to return two integer values ββfrom your function (then you will not need external parameters). You can manually unpack the first and second elements into your x and y variables, or you can implement a helper class for this. For instance:
std::pair<int, int> getvals () { std::pair<int, int> p; std::cin >> p.first; std::cin >> p.second; return p; } template <typename T, typename U> struct std_pair_receiver { T &first; U &second; std_pair_receiver (T &a, U &b) : first(a), second(b) {} std::pair<T, U> operator = (std::pair<T, U> p) { first = p.first; second = p.second; return p; } }; template <typename T, typename U> std_pair_receiver<T, U> receive_pair (T &a, U &b) { return std_pair_receiver<T, U>(a, b); } int main () { int x, y; receive_pair(x, y) = getvals();
If you have C ++ 11, you can use the more general tuple and tie helper to do it in a similar way in a cleaner way. This is illustrated in Benjamin Lindley's answer.
source share