6.2 — Giving back a value (return)
Read one box at a time. No rush.
Functions that answer#
A function can work something out and return the answer.
C++▶ Run
int getFavouriteNumber(){ return 7;} int main(){ int n { getFavouriteNumber() }; std::cout << n << '\n'; // 7 return 0;}- The type before the name (
int) is the return type: what kind of value comes back. return 7;sends the value back and ends the function.
void means nothing back#
If a function does not return anything, its return type is void.
C++
void printLine(){ std::cout << "----------\n";}Using the answer#
The returned value can be used anywhere a value fits:
C++
std::cout << getFavouriteNumber() * 2; // 14Watch out
A function that says it returns int must return a value. Forgetting return is undefined behavior. Your compiler will usually warn you.
Why main returns 0#
main returns an int to the operating system. 0 means "all good". Any other number usually means "something went wrong".
Tip: press ← / → to move between lessons, / to search.