Cpp - Auto-Typed Return Values

Introduction

To make a function's return type determined by deduction, use auto where the return type is specified, as in this simple function:

auto subtract(int x, int y) 
{ 
    return x - y; 
} 

Because both x and y are integers, the sum of subtracting one from the other also is an int.

If a function has more than one return statement, they all must return the same data type.

Demo

#include <iostream> 
 
auto findArea(int length, int width = 20, int height = 12); 
 
auto findArea(int length, int width, int height) 
{ 
    return (length * width * height); 
} 
 
int main() // ww  w.  ja v  a  2s  .c  om
{ 
    int length = 100; 
    int width = 50; 
    int height = 2; 
    int area; 
 
    area = findArea(length, width, height); 
    std::cout << "First area: " << area << "\n\n"; 
 
    area = findArea(length, width); 
    std::cout << "Second area: " << area << "\n\n"; 
 
    area = findArea(length); 
    std::cout << "Third area: " << area << "\n\n"; 
    return 0; 
}

Result

Related Topic