- Learn C++ Test Site - https://test.learncpp.com -

2.5 — Why functions are useful, and how to use them effectively

Now that we’ve covered what functions are and some of their basic capabilities, let’s take a closer look at why they’re useful.

Why use functions?

New programmers often ask, “Can’t we just put all the code inside the main function?” For simple programs, you absolutely can. However, functions provide a number of benefits that make them extremely useful in programs of non-trivial length or complexity.

Although it doesn’t look like it, every time you use operator<< or operator>> to do input or output, you’re using a function provided by the standard library that meets all of the above criteria.

Effectively using functions

One of the biggest challenges new programmers encounter (besides learning the language) is understanding when and how to use functions effectively. Here are a few basic guidelines for writing functions:

Typically, when learning C++, you will write a lot of programs that involve 3 subtasks:

  1. Reading inputs from the user
  2. Calculating a value from the inputs
  3. Printing the calculated value

For trivial programs (e.g. less than 20 lines of code), some or all of these can be done in function main. However, for longer programs (or just for practice) each of these is a good candidate for an individual function.

New programmers often combine calculating a value and printing the calculated value into a single function. However, this violates the “one task” rule of thumb for functions. A function that calculates a value should return the value to the caller and let the caller decide what to do with the calculated value (such as call another function to print the value).


2.6 -- Whitespace and basic formatting [1]
Index [2]
2.4 -- Introduction to local scope [3]