The C++ function conditional return statements 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: Passing a value to a function with conditional return statements in C++ programming

To show: How to return a value from a function with conditional return statements in C++ programming

 

// a function - demonstrates the multiple return statements

#include <iostream>

using namespace std;

 

// function prototype, receive long int type and return long int type

long int Doubler(long int AmountToDouble);

 

long int main(void)

{

  long int result = 0;

  long int input;

 

  cout<<"Enter a number to be doubled: ";

  cin>>input;

  cout<<"\nBefore Doubler() is called... ";

  cout<<"\ninput: "<<input<<" doubled: "<<result<<"\n";

  result = Doubler(input);

  cout<<"\nBack from Doubler()...\n";

  cout<<"\ninput: " <<input<< "   doubled: "<<result<<"\n";

  cout<<"Re run this program, input > 10000, see the output...\n";

 

  return 0;

}

 

long int Doubler(long int original)

{

if (original <= 10000)

return (original * 2);

else

{

cout<<"Key in less than 10000 please!\n";

return -1;

}

}

 

Output example:

 

Enter a number to be doubled: 100

Before Doubler() is called...

input: 100 doubled: 0

Back from Doubler()...

input: 100 doubled: 200

Re run this program, input > 10000, see the output...

Press any key to continue . . .

 

Enter a number to be doubled: 10100

Before Doubler() is called...

input: 10100 doubled: 0

Key in less than 10000 please!

Back from Doubler()...

input: 10100 doubled: -1

Re run this program, input > 10000, see the output...

Press any key to continue . . .

 

 

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