Functions in C++ are segments of code designed to execute a specific task and enhance code reusability, clarity, efficiency, and maintainability. They serve as the foundation of C++ programming. Therefore, whether you’re a novice or an adept coder, it’s essential to grasp how to utilize functions effectively and efficiently. In this article, we will explore the definition of a function in C++, the various types of functions, parameters and arguments, invoking functions, recursion, function overloading, and other unique kinds of functions in C++.
A function in C++ is a segment of code intended to carry out a designated task. Functions enable you to write a portion of the code once and utilize it as necessary. This characteristic of functions renders the program modular, simpler to understand, maintain, and troubleshoot. Thus, rather than duplicating the same logic repeatedly, the logic can be encapsulated within the function and invoked whenever required.
Basic Syntax of a Function:
return_type function_name(parameter_list) { // function body }
Parameters:
return_type: This is the datatype of the value that the function will output.
function_name: This is the identifier for the function.
parameter_list: This refers to a list of input parameters, which may be empty.
Function body: This consists of the set of instructions that determine what the function executes.
Example:
Cpp
Code Copied!
var isMobile = window.innerWidth “);
editor80926.setValue(decodedContent); // Set the default text
editor80926.clearSelection();
editor80926.setOptions({
maxLines: Infinity
});
function decodeHTML80926(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard80926() {
const code = editor80926.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(“.maineditor80926 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor80926 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}
function runCode80926() {
var code = editor80926.getSession().getValue();
function closeoutput80926() {
var code = editor80926.getSession().getValue();
jQuery(“.maineditor80926…
“““html
.code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn80926”).addEventListener(“click”, copyCodeToClipboard80926);
document.getElementById(“runBtn80926”).addEventListener(“click”, runCode80926);
document.getElementById(“closeoutputBtn80926”).addEventListener(“click”, closeoutput80926);
Output:
This script illustrates how the function greet() is crafted and subsequently invoked from the main() function to display “Hello from a function!” on the console.
Categories of Functions in C++
Functions in C++ are classified into two main categories:
Predefined Functions
User-created Functions
Predefined Functions in C++
Predefined functions in C++ refer to the functions that are built into the C++ standard libraries. They assist in carrying out common tasks like mathematical computations, input/output processing, and string manipulation. These are also referred to as Library functions.
Category
Functions
Header File
Purpose
Mathematical
sqrt(), pow(), abs()
<cmath>
Conduct standard math operations
Character Processing
isalpha(), isdigit()
<cctype>
Verify character types (letter, digit, etc.)
String Handling
strlen(), strcpy(), strcmp()
<cstring>
Manipulate C-style strings
Input/Output
cin, cout, getline()
<iostream>
Manage input and output streams
Utility Functions
exit(), malloc()
<cstdlib>
General-purpose utilities
Time Functions
time(), clock()
<ctime>
Handle time and date
Example:
Cpp
Code Copied!
var isMobile = window.innerWidth “);
editor83700.setValue(decodedContent); // Populate the editor with default content
editor83700.clearSelection();
editor83700.setOptions({
maxLines: Infinity
});
function decodeHTML83700(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard83700() {
const code = editor83700.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
data: {
language: “cpp”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output83700”).html(“
"+data+"");
jQuery(".maineditor83700 .code-editor-output").show();
jQuery("#runBtn83700 i.run-code").hide();
}
})
}
function closeoutput83700() {
var code = editor83700.getSession().getValue();
jQuery(".maineditor83700 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn83700").addEventListener("click", copyCodeToClipboard83700);
document.getElementById("runBtn83700").addEventListener("click", runCode83700);
document.getElementById("closeoutputBtn83700").addEventListener("click", closeoutput83700);
Output:
This code demonstrates the use of the built-in sqrt function from the <cmath> library to compute and display the square root of 25 on the console.
User-defined Functions in C++
User-defined functions in C++ are the
``````html
functions that are developed by coders to execute specific functions. They also assist in keeping code reusable, structured, and more manageable. A user-defined function generally entails declaring, defining, and invoking the function.
function closeoutput41788() {
var code = editor41788.getSession().getValue();
jQuery(".maineditor41788 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn41788").addEventListener("click", copyCodeToClipboard41788);
document.getElementById("runBtn41788").addEventListener("click", runCode41788);
document.getElementById("closeoutputBtn41788").addEventListener("click", closeoutput41788);
Outcome:
The code demonstrates how a user-defined function add() is created to calculate the sum of two integers, a and b, and invoked in the main() function, resulting in the output of 8 printed to the console.
Parameters and Arguments in Functions in C++
Parameters refer to variables specified in the parentheses within a function definition.
Arguments are the actual values supplied to the function when it is invoked.
Sample:
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor38537.setValue(decodedContent); // Set the initial text
editor38537.clearSelection();
editor38537.setOptions({
maxLines: Infinity
});
function decodeHTML38537(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy the code to clipboard
function copyCodeToClipboard38537() {
const code = editor38537.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor38537 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor38537 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
``````html
2000);
}).catch(err => {
console.error("Issue copying code: ", err);
});
}
data: {
language: "cpp",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output38537").html("
"+data+"");
jQuery(".maineditor38537 .code-editor-output").show();
jQuery("#runBtn38537 i.run-code").hide();
}
})
}
function hideOutput38537() {
var code = editor38537.getSession().getValue();
jQuery(".maineditor38537 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn38537").addEventListener("click", copyCodeToClipboard38537);
document.getElementById("runBtn38537").addEventListener("click", executeCode38537);
document.getElementById("closeoutputBtn38537").addEventListener("click", hideOutput38537);
Output:
The code illustrates that the string name and int age are the parameters defined within the greet() function, and “Nirnayika”, 21, and “Pooja”, 25, serve as the arguments supplied when the greet() function is invoked.
Default Values in Functions in C++
Default values in C++ permit the assignment of initial values to the parameters of a function. If no argument is supplied for a parameter at the time of the function call, the default value is utilized automatically.
Example:
Cpp
Code Copied!
Output:
The code demonstrates the definition of a function greet() with a default argument “Guest”, invoked twice—first with “Yash” and then without any argument using the preset value—after which the result is displayed in the console.
Calling Functions in C++
Calling functions in C++ involves executing a function by its name. When a function is invoked, control shifts to the function body, processes the code within it, and thereafter returns to the point where the function was called.
There
``````html
There exist three techniques to invoke a function in C++:
Techniques
Overview
Illustration
Invocation by Value
A duplicate of the actual value is delivered, and modifications within the function do not influence the original value.
display(x)
Invocation by Reference
The genuine variable is sent, and alterations within the function impact the original value.
display(&x) (utilizing reference or pointer)
Invocation by Pointer
The location of the variable is passed, allowing for changes to the original value through pointers.
display(&x)
Illustration:
Cpp
Code Copied!
Outcome:
The code demonstrates that the original num 5 remains unchanged at 5 when the invocation by value technique is employed. However, when utilizing invocation by reference, it transforms to 25, and using invocation by pointer alters it to 55.
Recursion in C++
Recursion refers to a programming method where a function calls itself. A function that performs this is termed a recursive function. In recursion, there exist two primary scenarios: the base case, which is a criterion that halts recursion to avoid infinite calls, and the recursive case, where the function invokes itself with an altered or adjusted parameter. Recursion is applicable in tasks such as tree traversal, generating the Fibonacci sequence, and calculating factorials, etc.
This code illustrates how a recursive function, factorial(), is utilized to determine the factorial of the number 5. The function invokes itself until it reaches the base case (factorial(0)), which returns 1. Consequently, the main function outputs the factorial of 5 as the result.
Function Overloading in C++
Function overloading is a method of defining several functions that share the same name but differ in their parameter lists. The compiler evaluates which function to invoke based on the provided arguments.
There are two methods for overloading a function in C++:
Category
Explanation
By Number of Parameters
Functions carry the same name but vary in the count of parameters.
By Type of Parameters
Functions share the same name and parameter count but differ in types.
Example:
Cpp
Code Copied!
Output:
This code illustrates how a function can be overloaded by modifying the number and type of parameters sharing the same function name, add(), enabling the execution of various operations depending on the received arguments, and subsequently outputs the result to the console.
Function Local Variables in C++
Local variables in C++ refer to the variables declared within the confines of a function. These variables are instantiated when the function is invoked and are deconstructed once the function concludes, indicating that local variables are confined to the scope of their respective functions. While there are several approaches to access a local variable’s memory beyond its scope, using these methods incorrectly may lead to errors or unpredictable behavior.
Illustration:
Cpp
Code Copied!
Output:
This code demonstrates the definition of a local variable localVar within the show() function, which is only accessible within this function and not usable externally. Therefore, attempting to access it from the main function results in an error.
Function Pointers in C++
A function pointer is a pointer in C++ that references a function rather than a value. It enables
dynamically invoking functions at runtime, supplying functions as parameters to other functions, and creating collections of functions.
Syntax:
``````html
return_type (*pointer_name)(parameter_list);
Sample:
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor2264.setValue(decodedContent); // Set the default text
editor2264.clearSelection();
editor2264.setOptions({
maxLines: Infinity
});
function decodeHTML2264(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard2264() {
const code = editor2264.getValue(); // Fetch code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",
data: {
language: "cpp",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output2264").html("
"+data+"");
jQuery(".maineditor2264 .code-editor-output").show();
jQuery("#runBtn2264 i.run-code").hide();
}
});
}
function closeoutput2264() {
var code = editor2264.getSession().getValue();
jQuery(".maineditor2264 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn2264").addEventListener("click", copyCodeToClipboard2264);
document.getElementById("runBtn2264").addEventListener("click", runCode2264);
document.getElementById("closeoutputBtn2264").addEventListener("click", closeoutput2264);
Result:
The snippet illustrates how a function pointer, funcPtr, is utilized to hold the address of the greet() function and invoke it indirectly, hence displaying the message “Hello from Intellipaat!” upon execution.
Distinction Between Function and Function Pointer in C++
Factor
Function
Function Pointer
Explanation
A named block of code that executes a task.
A variable that contains the address of a function.
Invocation Method
Directly by its name.
Indirectly through the pointer.
Declaration Format
void greet();
void (*ptr)();
Assignment
Not necessary, defined only once.
Requires explicit assignment, such as ptr = greet;.
Memory Usage
Code resides in the code segment, no extra memory needed for access.
Pointer retains the address of a function.
Adaptability
Statically linked at compile-time.
Can be modified at runtime to point to various functions.
Functionality
Execute fixed roles.
Facilitate dynamic function selection and callbacks.
Illustrations
Typical applications, basic calculations.
Event-based applications, callbacks, plugins, and function tables.
Type Validation
Completely checked by the compiler.
Must conform to the precise function signature as a type mismatch leads to errors.
Complexity Level
Straightforward.
A bit more intricate.
Inline Functions in C++
An inline function is a unique function in C++ where the compiler attempts to incorporate the function code directly at the call site rather than executing a function call. This enhances execution speed by eliminating the function call overhead, making it optimal for compact and straightforward functions.
Structure:
inline return_type function_name(parameters) { // function body }
function closeoutput54325() {
var code = editor54325.getSession().getValue();
jQuery(".maineditor54325 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn54325").addEventListener("click", copyCodeToClipboard54325);
document.getElementById("runBtn54325").addEventListener("click", runCode54325);
document.getElementById("closeoutputBtn54325").addEventListener("click", closeoutput54325);
Output:
The snippet illustrates how the inline function square() is implemented to directly insert the multiplication logic where the square function is invoked, subsequently printing the square of 5 as 25 in the console output.
Difference between Function and Inline Function in C++
Aspect
Function
Inline Function
Definition
A function is defined with the return_type function_name().
A function that starts with the inline keyword.
Function Call Mechanism
A call to the function involves overhead.
The function's code is inserted directly where the function is invoked, thereby eliminating overhead.
Execution Speed
Slower due to function call overhead.
Quicker for small functions due to reduced overhead.
Memory
Consumes memory for the function's call stack.
Can increase code size due to multiple code insertions.
Best Use Case
Used for complex processes or infrequently called functions.
Ideal for small, commonly used functions.
Recursive Functions
Can be recursive.
Cannot be recursive (the compiler can't inline a recursive function).
Compiler's Role
The function's code exists separately, managed by the compiler.
The compiler attempts to replace the function invocation with the actual function code.
Code Bloat
No code bloat occurs.
Can lead to code bloat if the function is frequently called.
Lambda Functions in C++
A lambda function in C++ is an anonymous function that can be defined inline at the location where it's utilized. It's particularly useful for short-lived operations. It also removes the requirement for function pointers and enhances code clarity and maintainability.
function closeoutput49172() {
var code = editor49172.getSession().getValue();
jQuery(".maineditor49172 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn49172").addEventListener("click", copyCodeToClipboard49172);
document.getElementById("runBtn49172").addEventListener("click", runCode49172);
document.getElementById("closeoutputBtn49172").addEventListener("click", closeoutput49172);
Output:
The code illustrates how a lambda function named add is declared to compute the sum of two integers a and b, which is then executed to display the result of 5 plus 3, totaling 8, to the console as an output.
Distinction Between Function and Lambda Function in C++
Aspect
Function
Lambda Function
Definition
Established via a standard function declaration.
Declared inline using the []() syntax.
Name
It possesses a name.
It is nameless, lacking a designation unless assigned to a variable.
Syntax
return_type function_name(parameters) { body }
[capture](parameters) -> return_type { body }
Memory
Retained as a distinct function in memory.
Executed as a function object (a callable entity).
Functionality
It can be invoked multiple times and can possess parameters and return types.
It can capture variables from the surrounding context and is generally employed for brief, transient tasks.
Scope
It exists solely within the boundary of the function or globally.
It exists only where it is declared or when linked to a variable.
Performance
May incur overhead from function calls.
May decrease overhead, but can expand code size if excessively utilized.
const and constexpr Functions in C++
Both const and constexpr functions in C++ are utilized to define variables or functions evaluated during compile time.
Let’s briefly examine each function accompanied by examples in C++.
const Function
A const function in C++ is a member function of a class that employs the const keyword and restricts modification of any member variables of the object it pertains to. It is declared by appending const after the function signature. This enhances code safety and predictability. If an attempt is made to alter the value within the const function, the compiler generates an error.
Syntax:
return_type function_name(parameters) const { // function body (cannot modify object’s data) }
Example:
``````html
var isMobile = window.innerWidth ");
editor60958.setValue(decodedContent); // Set the default text
editor60958.clearSelection();
editor60958.setOptions({
maxLines: Infinity
});
function decodeHTML60958(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard60958() {
const code = editor60958.getValue(); // Fetch code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
data: {
language: "cpp",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output60958").html("
"+data+"");
jQuery(".maineditor60958 .code-editor-output").show();
jQuery("#runBtn60958 i.run-code").hide();
}
})
}
function closeoutput60958() {
var code = editor60958.getSession().getValue();
jQuery(".maineditor60958 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn60958").addEventListener("click", copyCodeToClipboard60958);
document.getElementById("runBtn60958").addEventListener("click", runCode60958);
document.getElementById("closeoutputBtn60958").addEventListener("click", closeoutput60958);
Output:
The code illustrates how a const member function, getValue(), retrieves the value 10 without altering the object, and subsequently outputs the result to the console.
constexpr Function
A constexpr function in C++ is executed at compile-time. It is utilized to generate a constant expression that enhances program performance. It is declared with the constexpr keyword preceding the function definition.
Syntax:
constexpr return_type function_name(parameters) { // must return a constant expression }
Example:
Cpp
Code Duplication Successful!
var isMobile = window.innerWidth ");
editor14162.setValue(decodedContent); // Set the default text
editor14162.clearSelection();
editor14162.setOptions({
maxLines: Infinity
});
function decodeHTML14162(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard14162() {
const code = editor14162.getValue(); // Fetch code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
function closeoutput14162() {
var code = editor14162.getSession().getValue();
jQuery(".maineditor14162 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn14162").addEventListener("click", copyCodeToClipboard14162);
document.getElementById("runBtn14162").addEventListener("click", runCode14162);
document.getElementById("closeoutputBtn14162").addEventListener("click", closeoutput14162);
Output:
The snippet illustrates how a constexpr function, area(), is employed to compute the area of a rectangle using length and width at compile-time, subsequently outputting the result, 50, to the console.
Distinction between const and constexpr Functions in C++
Aspect
const Function
constexpr Function
Objective
It ensures no alteration of the object state.
It permits compile-time evaluation of a function when feasible.
Application
It is utilized solely for class member functions.
It applies to both standard and member functions.
Evaluation time
It is consistently evaluated at runtime but assures safety.
It is assessed at compile-time if inputs are constant; otherwise, at runtime.
Syntax
return_type function_name() const {}
constexpr return_type function_name() {}
Limitations
It cannot change non-mutable members.
The function body must remain straightforward and valid within constant expressions.
Demonstration
int getValue() const;
constexpr int square(int x);
Advantage
It grants read-only access to object data.
It offers precomputed values and optimization opportunities.
Summary
Functions are sections of code designed in C++ to complete a specific task. Utilizing functions enhances code readability, modularity, and maintainability. Additionally, C++ offers various types of functions, such as user-defined functions, lambda functions, and inline functions. By grasping the concept of a function, its functioning, parameters, recursion, overloading, and certain specialized types of functions in C++, you can effectively use functions to develop a practical C++ program.
Function in C++ – FAQs
Q1. What constitutes a function in C++?
A function in C++ refers to a code block utilized to execute a specific task.
Q2. What varieties of functions exist in C++?
In C++, there are two categories of functions: built-in functions, supplied by C++ libraries, and user-defined functions, crafted by developers.
Q3. What is the concept of function overloading?
Function overloading is the technique enabling us to define several functions sharing the same name but varying in parameter types and counts.
Q4. How does a function differ from a function pointer?
The distinction lies in that a function represents a block of code, while a function pointer retains the address of a function.
Q5. When is it appropriate to use inline functions?
Inline functions should be utilized for smaller functions to minimize function call overhead.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.