All lessons

Functions

9 min · C++

Package code under a name so you can reuse it.

C++ · Functions0/5 cleared

Enemy 1 of 5

Why functions matter

A function packages up a block of code under a name so you can run that logic again from anywhere just by calling the name, instead of copy-pasting the same lines every time you need them. This makes programs shorter, easier to change (fix a bug once, in one place), and easier to reason about, since a well-named function tells the reader what it does without them needing to read its insides.

In C++, every function declares its return type (what kind of value it hands back) and the type of each parameter it accepts. int doubleIt(int n) reads as "a function named doubleIt, taking one int parameter named n, that returns an int." This is different from dynamically typed languages like Python, where you don't have to declare types up front. C++ wants to know in advance so it can check your code for type mistakes before it ever runs.

Functions used by main need to be defined (or at least declared) above the point where they're called. Typically that means writing helper functions above main in the file, which is why doubleIt appears before int main() in the example.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10