Function??

This is original program~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <conio>

int subtraction (int,int);

int main ()
{
	int x=5,y=3,z;
   z=subtraction (7,2);
   cout<<"The first result is "<<z<<'\n';
   cout<<"The second result is "<<subtraction(7,2)<<endl;
   cout<<"The third result is "<<subtraction(x,y)<<endl;
   z=4+subtraction(x,y);
   cout<<"The fourth result is "<<z<<'\n';
   getch();
   return 0;
}

int subtraction(int a, int b)
{
	int r;
   r=a-b;
   return (r);
}


Why can't I make the program like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <conio>

int subtraction (int,int);

int main ()
{
	int x=5,y=3,z,r;
   z=subtraction (7,2);
   cout<<"The first result is "<<z<<'\n';
   cout<<"The second result is "<<subtraction(7,2)<<endl;
   cout<<"The third result is "<<subtraction(x,y)<<endl;
   z=4+subtraction(x,y);
   cout<<"The fourth result is "<<z<<'\n';
   getch();
   return 0;
}

int subtraction(int a, int b)
{
	
   r=a-b;
   
}

I'm study function now...but don't understand how it works actually...
So what's the usage of return (r);? line 8 has been added with int r;
TQ...
return places a value on the stack that can be fetched be the caller of the function. without return it's undefined what's on the stack. The compiler should have at least warn you (if not error)
Stack is something like register?

Thanks...
well first of all the second one doesnt work because youre trying to use r outside of main where its declared. Also return will "return" the value you give it back to the place it was called. Example:
i could call int subtraction like so
 
int blah = subtraction(10,5);


blah is now equal to 5 because we "returned" r which is equal to 10 - 5.
The stack is a piece of memory where your local variables resides. Each function places it's variables on the top of the stack at the beginning and kind of remove them when the function is done. Just the return value isn't removed.

The parameters of a function are also placed on the stack for the called function
Thanks...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <conio>

void prevnext (int x, int&  prev, int&  next)
{
	prev = x-1;
   next = x+1;
}

int main()
{
	int x=100,y,z;
   prevnext (x,y,z);
   cout<<"Previous="<<y<< ", Next="<<z;
   getch ();
   return 0;
}


For the program above, can anyone explain a bit about the code in line 4? I mean why "x"no need to use "&"? TQ...
'x' is being passed by value, it makes a copy of the variable and then lets you use it. 'prev' and 'next' are being passed by reference, instead of making a copy of it, it lets the function that you're giving it to modify the original.
Thanks...
So can I use all pass by value or use all pass by reference inside the function?
Topic archived. No new replies allowed.