return is a keyword that ends a function (or member function). Depending on the function, return might return anything or nothing.
The following function calculates the square of an integer:
///Calculates the square of an integer int Square(const int x) { const int solution = x * x; return solution; }
If a function returns nothing (that is, a return type of void), one can omit the final return:
#include <iostream> void SayHello() { std::cout << "Hello\n"; //return; //No need to return from a void function }
Exception: main
The function main is special. It returns an integer error code of the program, where a zero denotes a no-failure run. When main's closing bracket is reached, the effect is equivalent to (Standard, 3.6.1.5):
Therefore, the following two pieces of code are equivalent:
return in a C++11 lambda expression
Program flow in a C++11 lambda expression differs from a C++98 lambda expression or BOOST_FOREACH: if you want to return from a function, all that happens is that the std::for_each (or other algorithm) is terminated. The example below shows this.
#include <algorithm> #include <cassert> #include <iostream> #include <vector> void TestProgramFlow() { //2-D std::vector, note 42 in the middle, from an initializer list const std::vector<std::vector<int> > v = { { 0, 1, 2, 3, 4 }, { 10,11,12,13,14 }, { 40,41,42,43,44 }, { 50,51,52,53,54 }, { 60,61,62,63,64 } }; //First lambda expression std::for_each(v.begin(),v.end(), [](const std::vector<int>& w) { //Nested second lambda expression std::for_each(w.begin(),w.end(), [](const int i) { if (i == 42) { std::cout << "FOUND!\n"; return; //Terminates the second lambda expression, //Does not return from Test function } } ); } ); //Will get here, as the return statement only terminates //the second lambda expression, instead of the Test function assert(!"Should not get here"); }
Screen output: