Function returning

Hello again!

I've been messing around with functions lately. I'm trying to understand return types with functions but It's not really working. Heres my problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int add(int a);

int main()
{
	int dogs = 6;
	cout << "Dogs = " << dogs << endl;  
	add(dogs);
	cout << "Dogs = " << dogs << endl;  
	return 0;
}

int add(int a)
{
	a += 4;
	return a;
}


When I run it, I get this
Dogs = 6
Dogs = 6

But I actually want this
Dogs = 6
Dogs = 10

It would be great if you guys could help me out :D
Well you're not using the value returned from the function so all you're doing is printing the unchanged dog variable twice.

To fix it either give dogs the return value or print the return value
(dogs = add(dogs);) (cout << "Dogs = << add(dogs) << endl;)
closed account (z05DSL3A)
change line 10 to dogs = add(dogs);
You can do with a reference variable instead of the variable dogs instead.
Sample this:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream.h>
using namespace std;
void add(int &a)        //Reference variable
{
	a += 4;

}
void main()
{ int dogs =6;
   cout << "Dogs = " << dogs << endl;  
   add(dogs);
   cout << "Dogs = " << dogs << endl;
  }
Last edited on
You could, but he mentions return types
Oh I get it. Thanks guys :D
Oh and this is a little off topic but whats the difference between a pointer and a reference? I know the syntax is different but how do they perform differently and when should I use one over the other?
They do not perform differently.

You'll get many differing opinions about when to use one over the other.

Mine is to use references (const or non-const) when possible. The exception to the case is when a function could, under normal working scenarios, be passed a NULL pointer. You can't (easily) pass NULL references.

So as examples, a function that sorts a list should take the list by non-const reference, unless you really intend to allow the user to pass a NULL pointer and do something other than return an error code or seg fault. A function that prints the contents of a list should take the list by const reference, unless again, you want to do something other than return an error or seg fault.
A pointer stores basically the memory location of a variable while a reference is simply an alternate name of an existing variable.

References are usually used in function calls while pointers have much diverse applications. But use them with care or you could end up crashing your system.
Topic archived. No new replies allowed.