Home > Articles > Programming > C/C++

C++ Without Fear: Functions

  • Print
  • + Share This
A function is a group of related statements that accomplish a specific task. Understanding functions is a crucial step to programming in C++, as Brian Overland explains in this chapter from his book.
This chapter is from the book

The most fundamental building block in the programming toolkit is the function—often known as procedure or subroutine in other languages. A function is a group of related statements that accomplish a specific task. Once you define a function, you can execute it whenever you need to do so.

Understanding functions is a crucial step to programming in C++: Without functions, it would be a practical impossibility to engage in serious programming projects. Imagine how difficult it would be to write a word processor, for example, without some means of dividing the labor. Functions make this possible.

The Concept of Function

If you’ve followed the book up until this point, you’ve already seen use of a function—the sqrt function, which takes a single number as input and returns a result.

double sqrt_of_n = sqrt(n);

This is not far removed from the mathematical concept of function. A function takes zero or more inputs—called arguments—and returns an output, called a return value. Here’s another example. This function takes two inputs and returns their average:

cout << avg(1.0, 4.0);

Once a function is written, you can call it any number of times. By calling a function, you transfer execution of the program to the function-definition code, which runs until it is finished or until it encounters a return statement; execution then is transferred back to the caller.

This may sound like a foreign language if you’re not used to it. It’s easy to see in a conceptual diagram. In the following example, the program 1) runs normally until it calls the function avg, passing the arguments a and b, and 2) as a result, the program transfers execution to avg. (The values of a and b are passed to x and y, respectively.)

The function runs until it encounters return, at which point: 3) execution returns to the caller of the function, which in this case prints the value that was returned. Then, 4) execution resumes normally inside main, and the program continues until it ends.

Note that only main is guaranteed to be executed. Other functions run only as called. But there are many ways a function can be called. For example, main can call a function A, which in turn calls B and C, which in turn calls D.

  • + Share This
  • 🔖 Save To Your Account