[Noob question] What does it mean by returning a value?

I'm currently on function tutorial page.
In laymans term what does it mean by "returning a value"
How do i know if the value returns something or not?
what does it mean by "returning a value"

Mmm, tricky. I'm not sure how much you know, so here's an example that print's PI.

If you did any trigonometry, you'll probably remember that PI = arc cos(-1).
1
2
3
4
5
6
7
#include <cmath>
#include <iostream>

int main()
{
        std::cout << "pi = " << acos(-1) << std::endl;
}

So acos is a function declared in header file cmath that calculates arc cosine. In the program, it returns a value that's passed to std::cout to be printed on the screen.

How do i know if the value returns something or not?
That's what declarations are. They tell the compiler (and you) what type things are.

The declaration of acos is shown here: http://www.freebsd.org/cgi/man.cgi?query=acos&apropos=0&sektion=0&manpath=FreeBSD+9.3-RELEASE&arch=default&format=html
You can see it is:

double acos(double x);

Simpler example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// function definition
int myFunction()
{

	return 4; // <-- this is the value you are returning from your function
}


int main()
{

	int num = 10;

	num = myFunction();

	return 0;  // <--  at this point 'num' would be 4
}
How do i know if the value returns something or not?

If you return a value, you are guaranteed to be returning something.

Garbage example:
1
2
3
4
int func_a ()
{  int x;  // uninitialized variable
    return x;  // Will return something, probably garbage
}


Only if the return type of a function is void, do you not have a return value.
1
2
3
4
void func_b ()
{  //  Do something
    return;  // No return value
}


Just because a function has a return value, doesn't mean that the calling code has to use it.
1
2
3
4
int main () 
{   func_a();  // return value ignored
    return 0;
}




for the simplest explanation and code
heres the code
1
2
3
4
5
int main()
{
 return 0; // if the program function main reached this return 0,in any function, it means that the programs is success without bug, 

}

second
1
2
3
4
5
6
int exFunction(int val1,int val2)
{
int result;
result= val1+val2
return result; //this return will return the val1+val2 which means if you use this function the the value will be added together..and only "add together " will happen
}



1
2
3
4
5
6
int exFunction ( int val1,int val2)
{
int result;
return val1+val2; // no difference in the 2nd snippet

}
Topic archived. No new replies allowed.