A function and its return statement C++ program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Declare and define C++ function that receive two floats from main(), return a float to main()

To show: How to declare, define and use function which returns a value in C++ programming

 

// program showing function definition, declaration, call and the use of the return statement

#include <iostream>

using namespace std;

 

int main(void)

{

float y1, y2, avgy;

 

cout<<"I'm in main(void)\n";

 

// a prototype for the function avg() that main() is going to call, a standard in C++ should be declared before defining the function

float avg(float, float);

 

y1=5.0;

y2=7.0;

 

cout<<"Again, I'm in main(void)\n";

 

// calling the function avg() i.e. control passes to avg() and the return value is assigned to avgy

avgy = avg(y1, y2);

 

cout<<"Back, I'm in main(void)\n";

cout<<"\ny1 = "<<y1<<"\ny2 = "<<y2;

cout<<"\nThe average is= "<<avgy<<endl;

 

return 0;

}

 

// definition of the function avg(), avg() receives two floats and return a float

float avg(float x1, float x2)

{

// avgx is a local to this function

float avgx;

 

cout<<"I'm in avg()\n";

// computes average and stores it in avgx.

avgx = (x1+x2)/2;

 

// returns the value in avgx to main() and control reverts to main()

return avgx;

}

 

Output example:

 

I'm in main(void)

Again, I'm in main(void)

I'm in avg()

Back, I'm in main(void)

y1 = 5

y2 = 7

The average is= 6

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index