Alright, I'm probably going to become the biggest pain in the butt here during the days to come, but please bear with me.

#include <iostream>
int Subtract(int first, int second)
{
	std::cout << "In Subtract(), recieved " << first << " and " << second << "\n";
	return (first - second);
}

int main()
{
	using std::cout;
	using std::cin;


	cout << "I'm in main()!\n";
	int a, b, difference;
	cout << "Enter two numbers: ";
	cin >> a;
	cin >> b;
	cout << "\nCalling Subtract()\n";
	difference=Subtract (a,b);
	cout << "\nBack in main().\n";
	cout << "difference was set to " << difference;
	cout << "\nExiting...\n\n";
	return 0;
}

I highlighted difference=Subtract (a,b), because I don't understand how this calls out the Subtract function.
Wouldn't you have to type in Subtract (a,b) then in another line make c=Subtract?

Recommended Answers

All 5 Replies

Well the program firsts calls main();
Then after that, Assigns space for 3 variables.

Then takes 2 values into the first two of its variables and then looks at

difference=Subtract(a,b);

During that it first calls the function Subtract(a,b) And then assigns the output value to the variable difference.

But Subtract is a function and not a variable. Hence Subtract(a,b) cannot store any value. Therefore the output val is taken.

Hope you understood it.. Coz my explaination may not be that clear.

move lines 10 and 11 up to between lines 1 and 2.

You should look at functions as a vendingmachine. You put some input in it (in your case two ints) and it gives you something back. That's what the return does in your function.
So you need something to put the returned value in. That what the 'difference' variable does. It stores the value returned by your function.

Here's a nice tutorial

[edit] And what Ancient Dragon said

@Sky. So, it wouldn't be problematic later to use (variable)=(function) (parameter) to call out a function? (nevermind understood already) Oh and niek_e put it in a much easier way to understand Hahaha (even though I do appreciate your help) Thank you to you and niek_e. /understood

@Ancient Alright. I did just copy it off SAMS, and I want to understand it more than I want to make it better. :D

Well it wouldnt be a problem at all as the function returns an int and your allocating that returned value to your variable.

It all depends upon how you define your function.

For example You can directly use cout in your function instead of return and avoid the line 20 in your code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.