C++ Functions

Hi everyone, inside this article we will see about C++ Functions.

A function in C++ is a block of code that performs a specific task and returns a value. Functions help you divide your code into smaller, reusable units, making it easier to write, debug, and maintain.

Syntax & Declaration of Function

In C++, you can define your own functions or use functions that are part of the standard library.

Here’s the general syntax for defining a function in C++:

return_type function_name(parameter_list) {
  // code to be executed
}

where:

  • return_type is the data type of the value returned by the function. If the function does not return a value, you can use void as the return type.
  • function_name is the name of the function. It should be descriptive and indicate what the function does.
  • parameter_list is a list of parameters that the function takes as input. Each parameter is defined with its data type and a name.

To call a function, you simply use its name followed by its parameters in parentheses:

function_name(parameter1, parameter2, ...);

Advantages of Using Functions in C++

There are several advantages to using functions in C++:

Improved code readability: Functions help to divide your code into smaller, manageable units, making it easier to read, understand, and maintain.

Reusability: Functions allow you to write code once and reuse it in multiple places, reducing the amount of code you need to write and maintain.

Improved modularity: Functions encourage you to think about your code in terms of modular, independent units, making it easier to isolate and fix bugs, and to add new features.

Abstraction: Functions allow you to hide the implementation details of a task, and present a simple, abstract interface to the calling code. This makes it easier to change the implementation of a function without affecting the code that calls it.

Improved efficiency: Functions can be optimized by the compiler to produce faster code, and by calling functions instead of duplicating code, you can reduce the size of your program and make it run faster.

Better error handling: Functions allow you to encapsulate error handling logic in a single place, making it easier to detect and correct errors, and to prevent them from spreading throughout your code.

Improved organization: Functions help to organize your code into logical, cohesive units, making it easier to understand and maintain, and to test and debug.

These are some of the key advantages of using functions in C++. By using functions effectively, you can improve the quality, reliability, and maintainability of your code, and make it easier to develop, test, and debug.

Types of C++ Functions

There are two types of functions in C++ programming:

Library Functions

In C++, library functions are pre-written functions that you can use in your own code. These functions are stored in libraries, which are collections of reusable code that can be linked to your program at compile time.

The C++ Standard Library provides a wide range of functions for a variety of tasks, including:

Input/Output: Functions for reading and writing data from/to the standard input and output streams (cin, cout), and for reading and writing files (fstream, ifstream, ofstream).

String handling: Functions for working with strings, such as concatenating strings, searching for substrings, and converting strings to numbers and vice versa (string, strcpy, strcmp, atoi, itoa).

Mathematical functions: Functions for performing arithmetic and mathematical operations, such as square roots, trigonometry, and logarithms (sqrt, sin, cos, log).

Dynamic memory allocation: Functions for allocating and freeing memory dynamically (new, delete, malloc, free).

Time and date: Functions for working with time and date values (time, date, clock, ctime).

Standard Template Library (STL): A collection of generic, reusable data structures and algorithms for tasks such as sorting, searching, and manipulating collections of data (vector, list, stack, queue, map, set).

These are just a few examples of the types of functions you can find in the C++ Standard Library. By using library functions, you can save time and effort by reusing existing, well-tested code, rather than having to write everything from scratch. Additionally, by using library functions, you can be confident that your code will be portable, since the behavior of library functions is standardized across all platforms and compilers.

User-defined Functions

In C++, user-defined functions are functions that you write yourself to perform specific tasks in your program. These functions can be defined anywhere in your code, and can be called from anywhere else in your code.

All above mentioned are the benefits of using user-defined functions in C++.

Inline Functions

These are functions that are expanded in line with the code that calls them, rather than being executed as separate functions. This can result in a performance improvement for small functions.

Recursive Functions

These are functions that call themselves in order to perform a task. Recursive functions are useful for solving problems that can be broken down into smaller sub problems.

Friend Functions

These are functions that are declared as friends of a class. They have access to the private and protected members of the class and can be called like any other non-member function.

Default Arguments

These are functions that have default values specified for some of their arguments. If a value is not provided for these arguments, the default value is used.

Overloaded Functions

These are functions that have the same name, but different arguments. Overloaded functions are useful for performing different actions depending on the type or number of arguments passed to the function.

A Basic Example

To define a user-defined function in C++, you use the function keyword, followed by the function name, a list of parameters (if any), and a block of code that implements the function.

Example #1

#include <iostream>
using namespace std;

void printHelloWorld()
{
    cout << "Hello, World!" << endl;
}

int main()
{
    printHelloWorld();
    return 0;
}

When you run this program, it will call the printHelloWorld function, and print the message “Hello, World!” to the screen.

Output

Hello, World!

Example #2

#include <iostream>
using namespace std;

void func()
{
    static int i = 0; // static variable
    int j = 0;        // local variable
    i++;
    j++;
    cout << "i=" << i << " and j=" << j << endl;
}

int main()
{
    func();
    func();
    func();
}

The function func contains both a static and a local variable. The static keyword is used to declare a static variable, which retains its value between function calls. The local variable j is defined within the function, and is initialized to 0 each time the function is called.

When the func function is called three times, the value of i is incremented each time, but the value of j is reset to 0 each time the function is called.

Output

i=1 and j=1
i=2 and j=1
i=3 and j=1

As a result, the output shows that the value of i is increasing each time the function is called, but the value of j is always 1.

We hope this article helped you to understand about C++ Functions in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.