Introduction to Functions
Introduction to Functions
Functions Fundamentals
Introduction to Functions
A function is a section of code that performs an action that other sections of a program can refer to. You create a function by writing code. The fundamental formula to create a function is:
options function-name(...)
{
}
Practical Learning: Introducing Functions
#include <iostream>
using namespace std;
int main()
{
int miles = 0;
double pieceworkRate = 0.00;
cout << "====================================";
cout << "\n - Piece Work Delivery -";
cout << "\n====================================";
cout << "\nMiles Driven: " << miles;
cout << "\nPiecework Rate: " << pieceworkRate;
cout << "\n====================================";
}============================================ - Piece Work Delivery - ============================================ Miles Driven: 0 Piecework Rate: 0.00 ============================================ Press any key to close this window . . .
The creation of a function starts with some options. As the simplest option you can apply, start a function with a keyword named void (that keyword is required for now).
The Name of a Function
A function must have a name. That name must follow some rules:
The Parentheses of a Function
The name of a function is followed by parentheses. At a minimum, the parentheses can be empty. Most of the time, you will write the parentheses on the same line as the name of the function. Otherwise, you can write each parenthesis on its own line. Here is an example:
void CarryMe ( )
Or like this:
void CarryMe(
)
Or like this:
void CarryMe
(
)
The Body of a Function
The body of a function follows the parentheses. After the parentheses, add the brackets: { and }. Here are examples:
void Send(){} void Publish(){ } void Salute( ){} void Continue( ){ } void Announce (){} void CarryMe ( ) { }
The section between the curly brackets is the body of the function. In that body, you can write the code that describes what the function is supposed to do.
Practical Learning: Creating Functions
#include <iostream> using namespace std; int miles = 0; double pieceworkRate = 0.00; // A function that requests a value void GetMiles() { cout << "Miles Driven: "; cin >> miles; } // Another function that requests a value void GetWorkRate() { cout << "Piecework Rate: "; cin >> pieceworkRate; } int main() { cout << "===================================="; cout << "\n - Piece Work Delivery -"; cout << "\n===================================="; cout << "\nMiles Driven: " << miles; cout << "\nPiecework Rate: " << pieceworkRate; cout << "\n===================================="; }
Calling a Function
After creating a function, you can use it. Using a function is referred to as calling it. To call a simple function like the one we created above, type its name, followed by parentheses, and end it with a semicolon. This would be done as follows:
void Publish(){
}
Publish();
Practical Learning: Calling Functions
#include <iostream>
using namespace std;
int miles;
double pieceworkRate;
void GetMiles()
{
Write("Miles Driven: ");
cin >> miles;
}
void GetWorkRate()
{
Write("Piecework Rate: ");
cin >> pieceworkRate;
}
int main()
{
cout << "==============================================================";
cout << "\n - Piece Work Delivery -";
cout << "\n==============================================================";
cout << "\nTo evaluate the employee's pay, type the following information";
GetMiles();
GetWorkRate();
cout << "\n==============================================================";
cout << "\nPay Summary");
cout << "\n--------------------------------------------------------------";
cout << "\nMiles Driven: " << miles;
cout << "\nPiecework Rate: " << pieceworkRate;
cout << "\n==============================================================";
}============================================================== - Piece Work Delivery - ============================================================== To evaluate the employee's pay, type the following information Miles Driven: 1417 Piecework Rate: .47 ============================================================== Pay Summary -------------------------------------------------------------- Miles Driven: 1417 Piecework Rate: 0.47 ============================================================== Press any key to close this window . . .
The Scope and Lifetime of a Variable
Introduction
The scope of a variable is the extent to which it is available to other members of a project. To manage this, a variable is said to have local or global scope.
Local Variables
A variable is said to be local if it is declared in the body of a function. Here is an example:
void Create()
{
string middleName;
}
When a variable is declared as local, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error.
A Global Variable
A variable is said to be global if it is declared (directly) in the Code Editor; that is, outside any curly brackets or outside any function. Here is an example:
string strDateOfBirth;
void Initialize()
{
}
void Present()
{
}
A variable that has been declared globally can be accessed by any code of the same document.
A Function that Returns a Value
Introduction
As seen in our introduction, a function has a body, which is delimited by curly brackets. Still, to indicate the end of execution of a function, type the return keyword followed by a semicolon. Here are examples:
void Communicate()
{
return;
}
void NeedToDiscuss()
{
return;
}
void TakeCare()
{
return;
}
In this case, the return; statement doesn't serve any true purpose. It can be made useful when associated with a conditional statement.
Returning From a Function
A function can be made to return a value. That is, if a function doesn't produce an explicit value, set its return type to void. If a function must produce a value, write the data type on the left side of the name of the function you are creating. This would be done as follows:
double Calculate()
{
}
Then, before the closing curly bracket of the function, type the return keyword, followed by what to return, followed by a semicolon.
Returning a Value
The primary way to return from a function is with a value. Here are examples:
int ProduceANumber()
{
return 2000;
}
int GetTriple()
{
return 3000;
}
In this case, we say that the function is returning a value.
Returning a Variable
You can also return a variable. To do this, in the body of the function, declare a variable. If necessary, perform any operation you want. You can then assign a value or expression to the variable. Then, on the last line of the function, type return followed by the name of the variable, and a semicolon. Here are examples:
int nbr;
int GetNumber()
{
return nbr;
}
int GetTriple()
{
int result = Number * 3;
return result;
}
Topics on Calling a Function that Returns Something
Storing a Function Call in a Variable
If you have a function that produces a value and you use that value more than once, you can assign the function call to a variable and then use that variable as you see fit. Here is an example:
#include <iostream>
using namespace std;
int ProduceANumber()
{
return 2000;
}
int GetTriple()
{
return 3000;
}
int value = 3250;
double total = GetTriple();
int main()
{
cout << "Number: " << ProduceANumber();
cout << "\nTriple: " << total;
cout << "\n=============";
}
This would produce:
Number: 2000 Triple: 3000 ============= Press any key to close this window . . .
Returning an Expression
We already know that, in a function, you can declare one or more variables, perform some operations on the values, ant then return a value that represents an operation. Such an operation may produce an expression, and you may want to return such an expression. In some cases, you can perform the operations, store the result in a variable, then then return that variable. Consider the following example:
#include <iostream> using namespace std; string GetFullName() { string fName, mName, lName; cout << "Enter the employee name."; cout << "\nFirst Name: "; cin >> fName; cout << "Middle Name: "; cin >> mName; cout << "Last Name: "; cin >> lName; // Creating an expression to return and storing that expression in a variable string complete = fName + " " + mName + " " + lName; // Returning a variable return complete; } int main() { string fullName = GetFullName(); cout << "\n======================================="; cout << "\nEmployee Name: " << fullName; cout << "\n======================================="; }
Here is an example of running the program:
Enter the employee name. First Name: Michael First Name: Justin First Name: Carlock ======================================= Employee Name: Michael Justin Carlock =======================================
In some cases, you don't need to first store the expression in a variable and return that variable. You can just return the expression. Here is an example:
#include <iostream> using namespace std; string GetFullName() { string fName, mName, lName; cout << "Enter the employee name."; cout << "\nFirst Name: "; cin >> fName; cout << "Middle Name: "; cin >> mName; cout << "Last Name: "; cin >> lName; // Returning an expression return fName + " " + mName + " " + lName; } int main() { string fullName = GetFullName(); cout << "\n======================================="; cout << "\nEmployee Name: " << fullName; cout << "\n======================================="; }
Calling a Function Where it is Needed
Normally, when you call a function and assign the call to a variable, you are probably planning to use the returned value many times. If you are not planning to use the returned value many times, you can call the function directly where its value is needed. Here are examples:
#include <iostream>
using namespace std;
double Doubler()
{
double number = 973.64;
return number + number;
}
double Tripler()
{
double a = 244.47;
double threeTimes = a + a + a;
return threeTimes;
}
int main()
{
cout << "Numbers";
cout << "\n==============================";
cout << "\nTwo times of 973.64 is " << Doubler();
cout << "\n------------------------------";
cout << "\nThe triple of 244.47 is " << Tripler();
cout << "\n==============================";
});
This would produce:
Numbers ============================== Two times of 973.64 is 1947.28 ------------------------------ The triple of 244.47 is 733.41 ============================== Press any key to close this window . . .
Returning a Function Call
Imagine you have a function that returns a value. Imagine that you have to call that function in the body of another function to get the returned value of that function. Here is an example:
#include <iostream> using namespace std; double number = 973.64; double Doubler() { return number + number; } double TwoTimer() { cout << "Number"; double result = Doubler(); double a = 244.47; double threeTimes = a + a + a; cout << "\n--------------------------------"; cout << "\nThe triple of 244.47 is " << threeTimes; return result; } int main() { cout << "\n973.64 + 973.64 = " << TwoTimer(); cout << "\n================================"; }
This would produce:
Number -------------------------------- The triple of 244.47 is 733.41 973.64 + 973.64 = 1947.28 ================================ Press any key to close this window . . .
Notice that you have a function that returns a value produced by calling another function. In such a case, instead of storing the returned value of the function in a variable, you can call the function directly on the return line. Here are examples:
#include <iostream>
using namespace std;
int nbr;
int MultiplyBy4()
{
return nbr * 4;
}
int Calculate()
{
int u = 38;
int w = nbr * 3;
return u + w;
}
int GetNumber()
{
int x = 428;
nbr = x;
return MultiplyBy4();
}
int Summarize()
{
int y = 3258;
nbr = y * 8;
return Calculate();
}
int main()
{
nbr = 44;
cout << "Number: " << nbr << '\n';
cout << "Summary: " << Summarize() << '\n';
cout << "================";
}
This would produce:
Number: 44 Summary: 78230 ================ Press any key to close this window . . .
Declaring a Function
Introduction
In previous sections and lessons, we saw how to declare a variable before using it. That feature is also available for functions, with rules based on functions.
Declare a function consists of presenting its syntax in one section of the code, and the defining that functionin another section. You have many options.
To declare a function, somewhere in a C++ document, type the return value of the function, its name, its parentheses, and a semicolon.
Declaring a Function in a Function
The primary way to declare a function is to do it in a function where the declared function is going to be used. Outside the primary function, you can define the function you had declared. Here is an example:
#include <iostream>
using namespace std;
int main()
{
// Declaring a function
void Message();
cout << "We will start with the student registration process.\n";
// Calling the Message() function
Message();
}
void Message()
{
cout << "\nWelcome to the Red Oak High School.";
}
This would produce:
We will start with the student registration process. Welcome to the Red Oak High School. Press any key to close this window . . .
In the above code pieces, we declared only one function. In the same way, you can declare as many functions as you want. Use the functions throughout the document. Before the end of the document, define the functions. Here are examples:
#include <iostream>
using namespace std;
string fName, lName;
double hSalary, tWorked;
int main()
{
// Declaring a function
string GetFirstName();
string GetLastName();
double RequestBaseSalary();
double RequestTimeWorked();
void DisplaySummary();
cout << "Enter the following pieces of information about the employee.\n";
fName = GetFirstName();
lName = GetLastName();
cout << "-----------------------------------------\n";
cout << "Enter the value to calculate the salary.\n";
hSalary = RequestBaseSalary();
tWorked = RequestTimeWorked();
// Display the payroll summary
DisplaySummary();
cout << "\n========================================\n";
}
string GetFirstName()
{
string name;
cout << "First Name: ";
cin >> name;
return name;
}
string GetLastName()
{
string name;
cout << "Last Name: ";
cin >> name;
return name;
}
double RequestBaseSalary()
{
double sal;
cout << "Hourly Salary: ";
cin >> sal;
return sal;
}
double RequestTimeWorked()
{
double time;
cout << "Time Worked: ";
cin >> time;
return time;
}
void DisplaySummary()
{
cout << "========================================\n";
cout << "Payroll Summary\n";
cout << "----------------------------------------\n";
cout << "Employee name: " << fName << " " << lName << '\n';
cout << "Hourly Salary: " << hSalary << '\n';
cout << "Time Worked: " << tWorked << '\n';
cout << "Weekly Salary: " << hSalary * tWorked;
}
Here is an example of running the program:
Enter the following pieces of information about the employee. First Name: Andrea Last Name: Dobson ----------------------------------------- Enter the value to calculate the salary. Hourly Salary: 26.37 Time Worked: 38.50 ======================================== Payroll Summary ---------------------------------------- Employee name: Andrea Dobson Hourly Salary: 26.37 Time Worked: 38.5 Weekly Salary: 1015.25 ======================================== Press any key to close this window . . .
The rule in the above code is that, whether a function is formally defined or not, the compiler needs to be aware of the syntax of a function before that function is called.
Deferred Definition of a Function
The ability to declare a function before defining it is referred to as deferred definition. The most common way to declare the function is to do it in the top section of a C++ document, use the function where necessary in the document; then, before the end of the document, define the function. Here is an example:
#include <iostream> using namespace std; void Message(); int main() { cout << "We will start with the student registration process.\n"; Message(); } void Message() { cout << "\nWelcome to the Red Oak High School."; }
In the above code, we declared only one function. If necessary, you declare as many functions as you want. Here are examples:
#include <iostream>
using namespace std;
string GetFirstName();
string GetLastName();
double RequestBaseSalary();
double RequestTimeWorked();
void ProcessPayroll();
int main()
{
ProcessPayroll();
cout << "\n========================================\n";
}
string GetFirstName()
{
string name;
cout << "First Name: ";
cin >> name;
return name;
}
string GetLastName()
{
string name;
cout << "Last Name: ";
cin >> name;
return name;
}
double RequestBaseSalary()
{
double sal;
cout << "Hourly Salary: ";
cin >> sal;
return sal;
}
double RequestTimeWorked()
{
double time;
cout << "Time Worked: ";
cin >> time;
return time;
}
void ProcessPayroll()
{
cout << "Enter the following pieces of information about the employee.\n";
string firstName = GetFirstName();
string lastName = GetLastName();
cout << "-----------------------------------------\n";
cout << "Enter the value to calculate the salary.\n";
double hSalary = RequestBaseSalary();
double tWorked = RequestTimeWorked();
cout << "========================================\n";
cout << "Payroll Summary\n";
cout << "----------------------------------------\n";
cout << "Employee name: " << firstName << " " << lastName << '\n';
cout << "Hourly Salary: " << hSalary << '\n';
cout << "Time Worked: " << tWorked << '\n';
cout << "Weekly Salary: " << hSalary * tWorked;
}
Functions and Header Files
Creating and Using a Header File
In previous lessons, we learned that one way to manage variables was to declare them in a header file. This feature is also avaible for functions. This means that you can start by declaring one or more functions in a header file. Here is an example:
Header File: StaffMember.h
#pragma once
#include <iostream>
using namespace std;
string GetFirstName();
string GetLastName();
double RequestBaseSalary();
double RequestTimeWorked();
void ProcessPayroll();
Using a Source File
As you may know already, after creating a header file and making declarations in it, you can access its contents from a source file. You have many options. The most basic way to use the content of a header it to access it from the file that contains the main() function. To start, in that file, type #include and the name of the file inside the double-quotes. Of course, the file name must include its extension. After doing that, yyou can call the function(s) is (are) declared in the header file.
Another way you can use a header file is to associate a source file to a header file. To proceed, you can create a C++ source that has any name but with the .cpp extension. In that file, you can call any function from the header file. Here is an example:
Header File: StaffMember.h
#pragma once
#include <iostream>
using namespace std;
string GetFirstName();
string GetLastName();
double RequestBaseSalary();
double RequestTimeWorked();
void ProcessPayroll();
By tradition, the source file has the same name as the header file. As far as the operating system is concerned, those files differ by their extension (.h and .cpp respectively). Here is an example:
Source File: StaffMember.cpp
#include <iostream>
#include "StaffMember.h"
using namespace std;
string GetFirstName()
{
string name;
cout << "First Name: ";
cin >> name;
return name;
}
string GetLastName()
{
string name;
cout << "Last Name: ";
cin >> name;
return name;
}
double RequestBaseSalary()
{
double sal;
cout << "Hourly Salary: ";
cin >> sal;
return sal;
}
double RequestTimeWorked()
{
double time;
cout << "Time Worked: ";
cin >> time;
return time;
}
void ProcessPayroll()
{
cout << "Enter the following pieces of information about the employee.\n";
string firstName = GetFirstName();
string lastName = GetLastName();
cout << "-----------------------------------------\n";
cout << "Enter the value to calculate the salary.\n";
double hSalary = RequestBaseSalary();
double tWorked = RequestTimeWorked();
cout << "========================================\n";
cout << "Payroll Summary\n";
cout << "----------------------------------------\n";
cout << "Employee name: " << firstName << " " << lastName << '\n';
cout << "Hourly Salary: " << hSalary << '\n';
cout << "Time Worked: " << tWorked << '\n';
cout << "Weekly Salary: " << hSalary * tWorked;
}
After creating the source file and defining the function(s) that was (were) defined in the header file, in the file that contains the main() function, you can simply call the function(s) from the header file and you would get the results defined in the associated source file. Of course, you must reference (#include) the header file. Here is an example:
#include <iostream>
#include "StaffMember.h"
using namespace std;
int main()
{
ProcessPayroll();
cout << "\n========================================\n";
}
|
|
|||
| Previous | Copyright © 2000-2026, FunctionX | Tuesday 01 October 2025, 14:53 | Next |
|
|
|||