- Learn C++ - http://www.learncpp.com -

1.4b — 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 the code we’re putting inside the function just be put directly inside main?” In many cases (particularly for simple examples), it can. However, functions provide a number of benefits that make them extremely useful in non-trivial programs.

Although it doesn’t look like it, every time you use std::cin or std::cout 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 learning 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 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).

We’ll investigate this topic in more detail in lesson 1.10a -- How to design your first programs [1].

1.4c -- Keywords and naming identifiers [2]
Index [3]
1.4a -- A first look at function parameters and arguments [4]