Hello folks I have a question to ask in regard to functions and passing information between them. I'm taking an problem solving class and well the instructor went from simple cout and cin to functions and has been really vague since the class is mostly on problem solving and not supposed to focus on C++. Yeah.

Anyway my problem is just passing the values from one function to another. I'm trying to have the user input two numbers in one function (requirement of the assignment) and then calculate the sum of the numbers and print them in the second function. Sounds simple but for the life of me I can't get the functions to pass data and I don't really understand how the feature works anyway. I would appreciate it if someone could offer a better explaination of how this works and an idea on how I could get my solution. The code is below along with the current error.

error C2660: 'calcPrint' : function does not take 0 arguments

#include <iostream>
using namespace std;

int inputNumbers ()
	int num1, num2;
	cout << "Please enter the first number: ";			//Output to user for num1
	cin >> num1;										//Input from user to num1
	cout << "And now enter the second number: ";		//Output to user for num2
	cin >> num2;										//Input from user to num2
	return 0;

int calcPrint (int num1, int num2)
	int sum;
	sum = num1 + num2;
	cout << "You entered " << num1 << "and " << num2 << endl;
	cout << "The sum is " << sum << endl;
	return num1, num2;

int main ()
	inputNumbers ();			//Calls up inputNumbers function
	calcPrint ();				//Calls up CalcPrint function
	return 0;

Variables can be passed by value, in which case a copy of the value of the number is passed, not the number itself; or it can be passed by reference, in which case the number itself is passed. If passed by value then the value of the original variable in the called function remains unchanged. If passed by reference, then any changes to variable in the called function will be carried back to the calling function.

Remember you can only return a single variable from a function.

so, you want to able to use the values of the numbers entered in inputNumbers() after inputNumbers() closes so you should pass the variables you want input into to the function by reference, not declare them local to the called function. The return type of inputNumbers could be void, though returning an int and checking on the value of the int returned can be a way to make sure the function ended without fail or whatever.

On the other hand you don't want calcPrint to change the values of the varaibles passed back in main() so pass them by value, actually caculate the value of the sum of the two numbers before you try to print int and don't try returning the passed values back to the calling function.

This article has been dead for over six months. Start a new discussion instead.