Ad space (banner)
Lesson 6 / 20

Writing a Function

This lesson covers the basics of defining a function in C++. It's for anyone searching "C++ how to write a function."

A function bundles logic together under a name so it can be called as many times as you need. You define one in the form return-type functionName(parameters) { ... }.

The example defines a function, std::string greet(std::string name), that takes a name and builds and returns a greeting.

A common early mistake is a mismatch between the declared return type and the actual type of the value you return. C++ checks types at compile time, so a type mismatch produces an error, letting you catch the mistake before you even run the code.

In real projects, bundling the same logic into one function โ€” rather than copying it to multiple places โ€” makes fixing and maintaining code much easier.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C++ directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)