What's the difference between a function that returns and one that doesn't

At first I thought returned function were ones with equations, but it turns out void functions can be defined with values too, so I'm lost and can't tell when a should use a function with a return, and when I shouldn't.


Bonus Question: What's the difference between return0 and return10? (When the program runs, it pretty much looks like the same thing.)
All functions (well, almost all: we can safely ignore the few exceptions for now) return to the caller.

A function with a return type other than void returns to the caller with a result.

A function with a return type of void returns to the caller without a result
(Such functions are called for the side effects that they generate.)

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

int sum( int a, int b ) // function that returns a result of type int
{
    std::cout << "\t\t\tsum: about to return the result to the caller\n" ;
    return a+b ; // return to the caller with a result
}

void print_sum( int a, int b ) // function that does not return a result
{
    std::cout << "\tprint_sum: call sum\n" ;
    const int s = sum(a,b) ; // use the result that was returned
    std::cout << "\tprint_sum: sum finished executing and returned "
              << "the result " << s << " to the caller\n" ;

    std::cout << "\tprint_sum: " << a << " + " << b << " == " << s << '\n' ;

    std::cout << "\tprint_sum: about to return (without a result) to the caller\n" ;
    return ; // return to the caller (without a result)
             // note: this return statement (return without a result) may be omitted
}

int main()
{
    std::cout << "main: call print_sum\n" ;
    print_sum( 23, 78 ) ;
    std::cout << "main: print_sum finished executing and returned to the caller\n" ;
}

main: call print_sum
	print_sum: call sum
			sum: about to return the result to the caller
	print_sum: sum finished executing and returned the result 101 to the caller
	print_sum: 23 + 78 == 101
	print_sum: about to return (without a result) to the caller
main: print_sum finished executing and returned to the caller

http://coliru.stacked-crooked.com/a/4595c12ec042f6cc
Topic archived. No new replies allowed.