C++ Functions
C++ Functions
Marvin Ramos
C++ Functions
• A function is a block of code that performs a specific task.
• You can pass data, known as parameters, into a function.
Page | 1
• Functions are used to perform certain actions, and they are important for reusing code: Define the code once,
and use it many times.
• Dividing a complex problem into smaller chunks makes our program easy to understand and reusable.
Advantages of Functions
• Easier to code -Easier to Modify -Easier to Maintain
• Reusability -Less Programming Time -Easier to Understand
Function Prototype
• A function prototype is a declaration of a function that tells the program about the type of value returned by the
function, name of function, number and type of arguments.
• Return Type − A function may return a value. The return_type is the data type of the value the function returns.
Some functions perform the desired operations without returning a value. In this case, the return_type is the
keyword void.
• Function Name − This is the actual name of the function. The function name and the parameter list together
constitute the function signature.
Subject: Data Structures and Algorithms Prepared by: Mr. Marvin Ramos
• Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter.
This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
• Function Body − The function body contains a collection of statements that define what the function does.
Page | 2
Call a Function
• To call a function, write the function's name followed by two parentheses () and a semicolon ;
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Subject: Data Structures and Algorithms Prepared by: Mr. Marvin Ramos
Page | 7