C++ Function Return Statement

Introduction

Functions are of a certain type, also referred to as a return type, and they must return a value.

The value returned is specified by a return-statement.

Functions of type void do not need a return statement.

Example:

#include <iostream> 

void voidfn(); /*w w w.j  a va  2 s .c o m*/

int main() 
{ 
    voidfn(); 
} 

void voidfn() 
{ 
    std::cout << "This is void function and needs no return."; 
} 

Functions of other types (except function main) need a return-statement:

#include <iostream> 

int intfn(); //from w ww .ja v  a 2 s.  com

int main() 
{ 
    std::cout << "The value of a function is: " << intfn(); 
} 
int intfn() 
{ 
    return 42; // return statement 
} 

A function can have multiple return-statements if required.

Once any of the return- statement is executed, the function stops, and the rest of the code in the function is ignored:

#include <iostream> 

int multiplereturns(int x); 

int main() /*from w ww .  j  av  a2  s . c om*/
{ 
    std::cout << "The value of a function is: " << multiplereturns(25); 
} 

int multiplereturns(int x) 
{ 
    if (x >= 42) 
    { 
        return x; 
    } 
    return 0; 
} 



PreviousNext

Related