Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Chapter 4 Summary

Here are the main points of Chapter 4:

  • In C++, you can use functions to define a specific task, just as you might use a subroutine or procedure in another language. C++ uses the name function for all such routines, whether they return a value or not.
  • You need to declare all your functions (other than main) at the beginning of the program so that C++ has the type information required. Function declarations, also called prototypes, use this syntax:
    type  function_name (argument_list);
  • You also need to define the function somewhere in the program, to tell what the function does. Function definitions use this syntax:
    type  function_name (argument_list) {
        statements
    }
  • A function runs until it ends or until the return statement is executed. A return statement that passes a value back to the caller has this form:
    return expression;
  • A return statement can also be used in a void function (function with no return value) just to exit early, in which case it has a simpler form:
    return;
  • Local variables are declared inside a function definition; global variables are declared outside all function definitions, preferably before main. If a variable is local, it is not shared with other functions; two functions can each have a variable named i (for example) without interfering with each other.
  • Global variables enable functions to share common data, but such sharing provides the possibility of one function interfering with another. It’s a good policy not to make a variable global unless there’s a clear need to do so.
  • The addition-assignment operator (+=) provides a concise way to add a value to a variable. For example:
    n += 50;                // n = n + 50
  • C++ functions can use recursion—meaning they call themselves. (A variation on this is when two or more functions call each other.) This technique is valid as long as there is a case that terminates the calls. For example:
    int factorial(int n) {
        if (n <= 1)
           return 1;
        else
           return n * factorial(n – 1);  // RECURSION!
  • + Share This
  • 🔖 Save To Your Account