Mohamed Mahmoud's profile

Article about Functions in C++

 Functions in C++
Abstract:
In this article, you will find all about function in C ++; what kind of functions exist, and how to use them with examples.
In programming, a function refers to a section that collects code to perform a specific task.
Depending on whether the functionality is pre-defined or created by the programmer.

Keywords:
Definition, Declaration, Types of C++, advantages of using Functions, Calling a Function, C++, Create a Function.

Content:
1. Introduction  ........................................................................................3
2. C++ Functions…………………………………………………….......…...4
3. Create a function …………………………………………………............4
4. Defining a Function……………………………………………….............5
5. Types of function………………………………………………….............6
5.1. Library Function……………………………………..........………..…...7
5.2. User-defined Function……………………………………...........……..8
6. Function declaration………………………………………………..........10
7. Definition of function………………………………………………..........13
7.1. Call the value ……………………………………………………..........14
7.2. Call by Reference…………………………………………………........15
8. Advantages of Function……………………………………….……........16
9. C++ with Function…………………………………………….……..........16
10. Summary………………………………………………………................17
11. References…………………………………………………….........….…18

1. Introduction: [1]
A function may be a combination of statements that together perform a task. Every C++ program has a minimum of one function, which is main(), and every one of the foremost trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is such each function performs a selected task.
A function declaration tells the compiler a few function's name, return type, and parameters. A function definition provides the particular body of the function.
The C++ standard library provides numerous built-in functions that your program can call. For instance, function strcat() to concatenate two strings, function memcpy() to repeat one memory location to a different location, and lots of more functions.
A function is understood with various names sort of a method or a sub-routine or a procedure etc.

2. C++ Functions: [2]
A function may be a block of code that only runs when it's called.
You can pass data, referred to as parameters, into a function.
Functions are wont to perform certain actions, and that they are important for reusing code: Define the code once and use it repeatedly.

3. Create a function: [2]
C ++ provides some pre-defined functions, such as main (), which are used to execute code. But you will also create your own jobs to perform certain actions.
To create a function (often mentioned as an ad), specify the function name, followed by parentheses ():
Syntax
void myFunction() {
  // code to be executed
}
Example explained
myFunction () is that the function name.
A blank means that the function has no return value. You will learn more about return values later in the next chapter.
Inside the function (text), add a code that specifies what the job should do.

4. Defining a Function: [1]

The general definition of the C ++ function definition is as follows –
return_type function_name( parameter list ) {
 body of the function
}
The C ++ function definition consists of a function header and a function text. Below are all parts of the function -
Return type - the method may return a worth. Return_type is that the value data type that the method returns. It performs some functions by performing the specified operations without a valuable value. During this case, return_type is that the invalid keyword.
Function name - this is often the particular name of the function. Creates the function name and parameter list.
Parameters - the parameter as a placeholder. When a function is named, it passes a worth to the parameter. This value is mentioned as an actual parameter or argument. The parameter list indicates the sort, order, and number of function parameters. The parameters are optional; that's, a function might not contain parameters.
Function text - The function text contains a group of statements that outline what the function does.
Below is the source code for a function called max (). This function takes both the num1 and num2 parameters, and returns the largest of both –
// function returning the max between two numbers

int max(int num1, int num2) {
   // local variable declaration
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}

5. Types of function: [3]

5.1. Library Function: [3]

Library functions are the built-in function in C++ programming.
Programmers can use library function by invoking function directly; they do not need to write it themselves.
Example 1: Library Function
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double number, squareRoot;
    cout << "Enter a number: ";
    cin >> number;

    // sqrt() is a library function to calculate square root
    squareRoot = sqrt(number);
    cout << "Square root of " << number << " = " << squareRoot;
    return 0;
}
Output:
Enter a number: 26
Square root of 26 = 5.09902
In the example above, sqrt() library function is invoked to calculate the root of variety.
Notice code #include within the above program. Here, cmath may be a header file. The function definition of sqrt()(body of that function) is present within the cmath header file.
You can use all functions defined in cmath once you include the content of file cmath during this program using #include.
Every valid C++ program has at least one function, that is, main() function.

5.2. User-defined Function: [3]

C ++ allows the programmer to define his own Function.
A function code that a user selects to perform a specific task in which a set of code is named (ID).
When a function is called from any part of the program, it all executes the specified symbols within the function text.
How user-defined function works in C Programming?

Consider the figure above.
When the program starts running, the system calls the main function (), meaning that the system starts executing the symbols from the main function ().
When program control reaches function_name () within main (), it goes to function_name () null and all symbols are executed inside function_name () null.
After that, the program control moves to the main function where the code after the call is executed to function_name () as shown in the figure above.
Example 2: User Defined Function
C ++ program to add two whole numbers. Set the add () function to add integers and display the sum in the main () function.
#include <iostream>
using namespace std;

// Function prototype (declaration)
int add(int, int);

int main()
{
    int num1, num2, sum;
    cout<<"Enters two numbers to add: ";
    cin >> num1 >> num2;

    // Function call
    sum = add(num1, num2);
    cout << "Sum = " << sum;
    return 0;
}

// Function definition
int add(int a, int b)
{
    int add;
    add = a + b;

    // Return statement
    return add;
}
Output
Enters two integers: 8
-4
Sum = 4

6. Function declaration [4]

A minimal function declaration consists of the return type, function name, and parameter list (which could also be empty), alongside optional keywords that provide additional instructions to the compiler. The subsequent example may be a function declaration:
int sum(int a, int b);
The function definition consists of a declaration, in addition to the body, which is each symbol in curly brackets:
int sum(int a, int b)
{
    return a + b;
}
A function declaration followed by a semicolon may appear in multiple places during a program. It must appear before any calls thereto function in each translation unit. The function definition must appear just one occasion within the program, consistent with the One Definition Rule (ODR).
The required parts of a function declaration are:
The return type, which specifies the sort of the worth that the function returns, or void if no value is returned. In C++11, auto may be a valid return type that instructs the compiler to infer the sort from the return statement. In C++14, decltype(auto) is additionally allowed. For more information, see Type Deduction reciprocally Types below.
< >The function name, which must begin with a letter or underscore and can't contain spaces. generally , leading underscores within the Standard Library function names indicate private member functions, or non-member functions that aren't intended to be used by your code.The parameter list, a brace delimited, comma-separated set of zero or more parameters that specify the sort and optionally an area name by which the values could also be accessed inside the function body.Optional parts of a function declaration are:

< >constexpr, which indicates that the return value of the function may be a constant value are often computed at compile time.constexpr float exp(float x, int n)

{
    return n == 0 ? 1 :
        n % 2 == 0 ? exp(x * x, n / 2) :
        exp(x * x, (n - 1) / 2) * x;
};
< >Its linkage specification, extern or static.//Declare printf with C linkage.

extern "C" int printf( const char *fmt, ... );

< >Inline, which directs the compiler to replace each function call with the same function code. Inclusion can help with performance in scenarios where the function is executed quickly and it is called up repeatedly in a critical performance section of code.inline double Account::GetBalance()

{
return balance;
}
< >Noexcept, which specifies whether a function can throw an exception or not. In the following example, the function does not throw an exception if the is_pod expression is evaluated to true.#include <type_traits>


template <typename T>
T copy_object(T& obj) noexcept(std::is_pod<T>) {...}
< >The cv qualifiers, specifying if the function is const or volatile. Functions only)Virtual, override or final (member functions only). Virtual states that in a derivative class a function may be overridden. Override implies a function overrides a virtual function in a derived class. Final implies in any other related class a function cannot be overridden. See Virtual Functions for details.A static application for a member function (member functions only) means that the function is not connected to any object class instances.The ref-Qualifier that indicates for the compiler the overload of a function to choose when the implied object parameter (* this) is a value reference vs. a value reference. (Non static Member Functions only) See Function Overloading for more information.The figure below shows the function definition parts. The dark area is the body of the function.


7. Definition of function: [5]

Functions are called by their names. If the function is without argument, it are often called directly using its name. Except for functions with arguments, we've two ways to call them,
< >Call by ValueCall by Reference7.1. Call the value:
In this calling technique, we pass argument values that are stored or copied into the official parameters of the functions. Thus, the original values only changed the parameters inside the job changes.
void calc(int x);

int main()
{
    int x = 10;
    calc(x);
    printf("%d", x);
}

void calc(int x)
{
    x = x + 10 ;
}
Output =10
In this case, the particular variable x isn't changed, because we pass an argument by value, hence a replica of x is passed, which is modified, which copied value is destroyed because the function ends(goes out of scope). therefore the variable x inside main() still features a value 10.
But we will change this program to switch the first x, by making the function calc() return a worth, and storing that value in x.
int calc(int x);

int main()
{
    int x = 10;
    x = calc(x);
    printf("%d", x);
}

int calc(int x)
{
    x = x + 10 ;
    return x;
}
Output =20
7.2. Call by Reference
In this, we pass the address of the variable as arguments. during this case, the formal parameter are often taken as a reference or a pointer, in both the case they're going to change the values of the first variable.
void calc(int *p);

int main()
{
    int x = 10;
    calc(&x);     // passing address of x as argument
    printf("%d", x);
}

void calc(int *p)
{
    *p = *p + 10;
}
Output =20
8. Advantages of Function [6]
It is advantageous to create functions in a program. They
·Avoid codes repeating.

·Increase program readability.

·Divide a complex problem into many easier issues.

·Reduce error chances.

·It makes it easier to modify a program.

·Makes it possible to test the unit.

9. C++ with Function:

#include <iostream>
using namespace std;

int max3(int n,int m,int o); //function prototype

int main()
{
    int x,y,z,ans;
            cout<<" Input x, y, z:";
            cin>> x >> y >> z;
            ans = max3(x, y, z); // Function is called
            cout<<"Answer is: "<<ans<<endl;

    return 0;
}

int max3(int x, int y, int z){
int result=x;
            if(result < y) //if x is smaller then y
                        result = y; //output y
            if (result < z) //if x is smaller then z
                        result= z; //output z
    else

            return result;
}

10. Summary:

At last we know that function is a combination of statements that work together perform a task. And function is a block of codes that only runs when it's called. And you can pass data, referred to as parameters, into a function. Functions are wont to perform certain actions, and that they are important for reusing code: Define the code once and use it repeatedly.
To create a function (often mentioned as an ad), specify the function name, followed by parenthese ():
The C ++ function definition consists of a function header and a function text.
Types of function is Library Function and User-defined function. A minimal function declaration consists of the return type, function name, and parameter list (which could also be empty), alongside optional keywords that provide additional instructions to the compiler. We can define a function by Value and by Reference.
So Function has a big role in C++.
Article about Functions in C++
Published:

Owner

Article about Functions in C++

Published: