Technology Programming

How to Use Functions in C++

Things You'll Need

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.


Leave a reply