Writing & Using
Functions are an essential part of writing organized and maintainable C++ programs. They allow you to delegate tasks, making your code easier to test, reuse, and extend. In this page, you’ll learn why functions are important, how to write and use them, and where they can be defined in your projects.
Functions are a key tool for improving the structure and efficiency of your programs. Using functions promotes cleaner, more modular code, making your programs more efficient and easier to debug.
-
Delegation of Tasks: Functions allow you to break down complex problems into smaller, manageable tasks. Each function performs a specific job, making your code easier to understand and maintain.
-
Ease of Testing: By isolating tasks into functions, you can test them independently to ensure they work correctly before integrating them into your program.
-
Reusability: Functions can be reused across different parts of your program or even in future projects, saving time and effort.
-
DRY Principle: Functions help you adhere to the Don’t Repeat Yourself (DRY) principle by consolidating repetitive code into a single function, reducing redundancy and the chance of errors.
Writing and using functions in C++ involves a few straightforward steps:
-
Create the Prototype: Define the function’s return type, name, and parameter list at the beginning of your program or in a header file. This tells the compiler what the function looks like before its implementation.
int GetMin(int, int); -
Write the Implementation: Provide the actual code for the function, specifying how it performs its task. This is usually done after the main function or in a separate source file.
int GetMin(int x, int y) { return x <= y ? x : y; } -
Test It (Call It): Call the function from your main function or another part of your program to test its behavior and ensure it works as expected.
driver.cc // Copyright 2024 CSCE240#include <iostream>using std::cout;using std::endl;// Function to find the smallest valueint GetMin(int, int);int main() {const bool test1 = GetMin(1, 2) == 1;const bool test2 = GetMin(3, -3) == -3;const bool test3 = GetMin(4, 4) == 4;cout << "Test 1: " << test1 << endl;cout << "Test 2: " << test2 << endl;cout << "Test 3: " << test3 << endl;return 0;}int GetMin(int x, int y) { return x <= y ? x : y; }Terminal window cpplint driver.ccDone processing driver.ccg++ -Wall -std=c++17 driver.cc./a.outTest 1: 1Test 2: 1Test 3: 1
Functions can be written in various locations depending on the structure of your program and how you plan to use them.
In the Driver with main: When starting out, you’ll typically write your functions in the same source file as your
main function. This keeps everything in one place, making it easier to learn and test.
In Separate Source Files: Functions can also be written in separate source files without a main function. These files
can be compiled individually and linked into larger projects. This approach is useful for organizing code in larger programs.
In Header Files: Functions can be declared in header files and implemented in source files. This allows you to reuse them across multiple projects by simply including the header file.
The Prototype
Section titled “The Prototype”A function’s prototype is a declaration that specifies the structure of a function, including its name, return type, and parameter list. It serves as a promise to the compiler that the function will be implemented later in the program.
Key Points
Section titled “Key Points”- Single Statement: A prototype is a single statement and must end with a semicolon (
;). For example:
int Multiply(int x, int y);- Optional Parameter Names: Naming the parameters in the prototype is optional, but including them can improve readability:
int Add(int, int); // Validint Add(int a, int b); // Also valid and more descriptivePlacement: Prototypes should not appear inside the body of any other function. They must also precede all calls to the function, either at the top of the source file or in a header file.
The Implementation
Section titled “The Implementation”The implementation of a function provides the full definition, including how it performs its task. It consists of two main parts:
-
The Function Header: Specifies the return type, function name, and parameter list.
-
The Function Body: Contains the C++ commands enclosed in braces (
{}) that define the function’s behavior.
Key Points
Section titled “Key Points”- Named Parameters: Parameters must be named in the function header so they can be referenced within the function body. These parameters are local to the function, meaning they cannot be accessed outside of it.
int Add(int a, int b) { // 'a' and 'b' are local to this function return a + b;}-
No Semicolon: There is no semicolon between the function header and the opening brace of the body.
-
Separate Implementations: Each function must be implemented independently. One function cannot be implemented inside the body of another function.
Example
Section titled “Example”Lets create a calculator program that allows a user to add, subtract, multiply, and divide numbers they enter.
-
Setup File
Section titled “Setup File”-
We’ll create a document called
driver.cc, copyright the document, and create ourmainfunction. -
We want to print to the terminal and take user input so we’ll
#includethe<iostream>class and use thecin,cout, andendlobjects
driver.cc // Copyright 2024 CSCE240#include <iostream>using std::cin;using std::cout;using std::endl;int main() {return 0;} -
-
Create Function Prototypes
Section titled “Create Function Prototypes”-
We want to greet the user when the program is first run.
-
Lets give the user the ability to add, subtract, multiply, divide, and square integers they enter.
driver.cc // Copyright 2024 CSCE240#include <iostream>using std::cin;using std::cout;using std::endl;void Greet();int Add(int x, int y);int Subtract(int x, int y);int Multiply(int x, int y);double Divide(double num, double denom);int Square(int x);int main() {return 0;} -
-
Write Implementation
Section titled “Write Implementation”-
Below our
mainfunction, we’ll code the implementation of our functions. -
We’ll assume for this exercise that user input is ALWAYS correct.
driver.cc void Greet() {cout << "------------------------------------" << endl;cout << "Welcome to the CSCE240 Calculator!!!" << endl;cout << "------------------------------------\n" << endl;}int Add(int x, int y) { return x + y; }int Subtract(int x, int y) { return x - y; }int Multiply(int x, int y) { return x * y; }double Divide(double num, double denom) {if (num == 0 || denom == 0) {return 0;} else {return num / denom;}}int Square(int x) { return x * x; } -
-
Test Functions
Section titled “Test Functions”-
Lets write a couple of tests in our
mainfunction to check the implementation of our functions. -
Then we’ll check our styles and run the program.
driver.cc int main() {Greet();bool add_test = Add(4, 5) == 9;bool subtract_test = Subtract(0, 10) == -10;bool multiply_test = Multiply(3, 4) == 12;bool divide_test = Divide(1, 0) == 0;bool square_test = Square(5) == 25;cout << "Add: " << add_test << "\n"<< "Subtract: " << subtract_test << "\n"<< "Multiply: " << multiply_test << "\n"<< "Divide: " << divide_test << "\n"<< "Square: " << square_test << endl;return 0;}Terminal window cpplint driver.ccDone processing driver.ccg++ -Wall -std=c++17 driver.cc./a.out------------------------------------Welcome to the CSCE240 Calculator!!!------------------------------------Add: 1Subtract: 1Multiply: 1Divide: 1Square: 1-
Divide()is a little different than the rest of the functions, so we’ll call it a couple of times to see its output -
Finally we’ll recompile our program and run it to see the results.
driver.cc int main() {cout << Divide(1, 2) << endl;cout << Divide(0, 2) << endl;cout << Divide(10, 5) << endl;cout << Divide(-1, 1) << endl;return 0;}Terminal window g++ -Wall -std=c++17 driver.cc./a.out0.502-1 -
-
Create FrontEnd
Section titled “Create FrontEnd”-
We need to print a message for the user to notify them which options they have.
-
Lets declare another function prototype and add it to the others.
driver.cc void FrontEnd();- Now we need to write its implementation.
driver.cc void FrontEnd() {cout << "Enter 1: To Add" << endl;cout << "Enter 2: To Subtract" << endl;cout << "Enter 3: To Multiply" << endl;cout << "Enter 4: To Divide" << endl;cout << "Enter 5: To Square" << endl;cout << "Enter 0: To Quit" << endl;}-
This FrontEnd should remind you of the many programs written in CSCE146. What we are going to do is:
-
Wrap our code in a
whileloop. -
Print options to the user -> await input.
-
Direct that input to match a case in a
switchstatement. -
Get the required input to fulfill the requirements of that operation.
-
Print an output.
-
Repeat until the user quits the program.
-
-
This is the final version of our
mainfunction:
driver.cc int main() {Greet();bool run_program = true;while (run_program) {FrontEnd();int input;cin >> input;switch (input) {case 0:run_program = false;break;case 1: // Addcout << "Enter the first integer to add: " << endl;int first_add;cin >> first_add;cout << "Enter the second integer to add: " << endl;int second_add;cin >> second_add;cout << first_add << " + " << second_add << " = "<< Add(first_add, second_add) << "\n"<< endl;break;case 2: // Subtractcout << "Enter the first integer to subtract: " << endl;int first_sub;cin >> first_sub;cout << "Enter the second integer to subtract: " << endl;int second_sub;cin >> second_sub;cout << first_sub << " - " << second_sub << " = "<< Subtract(first_sub, second_sub) << "\n"<< endl;break;case 3: // Multiplycout << "Enter the first integer to multiply: " << endl;int first_mul;cin >> first_mul;cout << "Enter the second integer to multiply: " << endl;int second_mul;cin >> second_mul;cout << first_mul << " * " << second_mul << " = "<< Multiply(first_mul, second_mul) << "\n"<< endl;break;case 4: // Dividecout << "Enter the numerator: " << endl;int num;cin >> num;cout << "Enter the denominator: " << endl;int denom;cin >> denom;cout << num << " / " << denom << " = " << Divide(num, denom) << "\n"<< endl;break;case 5: // Squarecout << "Enter the integer you would like to square: " << endl;int square;cin >> square;cout << square << "^2 = " << Square(square) << "\n" << endl;break;default:cout << "Please enter an integer for the available options\n" << endl;}}cout << "Calculator powering off..." << endl;return 0;} -
-
Run and Test
Section titled “Run and Test”-
Finally we can run our program and test different inputs to see how it runs.
-
Instead of showing one long terminal log, I’ve parsed the output for each test:
Check Style, Compile, & Run
Section titled “Check Style, Compile, & Run”Terminal window cpplint driver.ccDone processing driver.ccg++ -Wall -std=c++17 driver.cc./a.outWrong Option Route
Section titled “Wrong Option Route”Terminal window ------------------------------------Welcome to the CSCE240 Calculator!!!------------------------------------Enter 1: To AddEnter 2: To SubtractEnter 3: To MultiplyEnter 4: To DivideEnter 5: To SquareEnter 0: To Quit9Please enter an integer for the available optionsAddition Route
Section titled “Addition Route”Terminal window Enter 1: To AddEnter 2: To SubtractEnter 3: To MultiplyEnter 4: To DivideEnter 5: To SquareEnter 0: To Quit1Enter the first integer to add:5Enter the second integer to add:55 + 5 = 10Subtraction Route
Section titled “Subtraction Route”Terminal window Enter 1: To AddEnter 2: To SubtractEnter 3: To MultiplyEnter 4: To DivideEnter 5: To SquareEnter 0: To Quit2Enter the first integer to subtract:5Enter the second integer to subtract:105 - 10 = -5Multiplication Route
Section titled “Multiplication Route”Terminal window Enter 1: To AddEnter 2: To SubtractEnter 3: To MultiplyEnter 4: To DivideEnter 5: To SquareEnter 0: To Quit3Enter the first integer to multiply:7Enter the second integer to multiply:77 * 7 = 49Division Route
Section titled “Division Route”Terminal window Enter 1: To AddEnter 2: To SubtractEnter 3: To MultiplyEnter 4: To DivideEnter 5: To SquareEnter 0: To Quit4Enter the numerator:100Enter the denominator:20100 / 20 = 5Squaring Route
Section titled “Squaring Route”Terminal window Enter 1: To AddEnter 2: To SubtractEnter 3: To MultiplyEnter 4: To DivideEnter 5: To SquareEnter 0: To Quit5Enter the integer you would like to square:99^2 = 81Quitting Route
Section titled “Quitting Route”Terminal window Enter 1: To AddEnter 2: To SubtractEnter 3: To MultiplyEnter 4: To DivideEnter 5: To SquareEnter 0: To Quit0Calculator powering off... -