How to Use Functions in C++
A function is code that can be executed repeatedly in a program. A C++ function consists of a label, an input argument list, a return type (if the function returns a value or else "void") and the function scope where the function algorithm is specified. To the compiler, the function scope is temporary memory that exists during function execution. An outside program defines, implements, overloads and calls functions.
Things You'll Need
- Basic C or C++
- A C++ compiler with an IDE
- A programming book in C++ or a mentor
Instructions
-
-
1
Define the function by writing its prototype. This is one line of code that consists of the function name, the argument list enclosed in parentheses, the return type and a semicolon. You write the prototype on top of the source file so that it will be visible to the compiler before it interprets how to the process the rest of the file.
-
2
Implement the function. That is, rewrite the prototype and enclose the algorithm within braces. Do this at the bottom of the source file and certainly below the prototype. The implementation requires that you give the input arguments a name (val in this case).
-
-
3
Overload a function. C++ permits what's called function overloading, a simple form of generic programming. It means that a function can be defined multiple times in the same compilation unit, as long as each definition has a unique argument list. This way, sin() can be defined to accept integers, floats or complex numbers and the library user doesn't have to be unreasonably careful about what data types to pass into sin().
-
4
Demonstrate the difference between passing variables by value and passing values by reference. These are the two modes of passing variables into functions in C++. Passing variables by value creates temporary copies of the variables in the temporary memory stack while the value of the passed variable doesn't change. Passing variables as references or pointers, on the other hand, lets the function modify the input variables directly.
-
5
Make a program call to the function. If you get a compiler error that says something like "unknown function," redefine the function at the top of the file where the call was made, this time preceding the definition with the "extern" keyword. This tells the compiler that the function is defined somewhere else and that it has to look for it somewhere else.
-
1
Tips & Warnings
In addition to standard functions C++ also offers Recursive Functions, Member Functions, Virtual Functions, Static Functions, In-Line Functions, and Pointers to Functions, but these are advanced topics and each of them deserves several articles.
A common programmer pitfall is to return variables that were declared inside the function scope. Remember, whatever is declared inside the stack space is destroyed by the compiler upon function exit, so you get an unpredictable result.