Skip to main content

C++ Functions


 




7.1 Function Basics


A function is a group of statements that together perform a task. All C programs made up of one or more functions. There must be one and only one main function.

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 so each function performs a specific task.


A program will be executing statements sequentially inside one function when it encounters a function call.

A function call is an expression that tells the CPU to interrupt the current function and execute another function.

The CPU 'puts a bookmark' at the current point of execution, and then calls (executes) the function named in the function call. When the called function terminates, the CPU goes back to the point it bookmarked, and resumes execution.


Function definition


return_type function_name( parameter list )

{

//statements

}


- The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value.


- function name is the identifier by which the function can be called.


- 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.


- statements is the function's body. It is a block of statements surrounded by braces { } that specify what the function actually does.


Example

/* Function returning addition of 2 integers */

int add(int a, int b)

{

int total ;

total= a+b;

return total;

}





7.2 Declaration, call & argument


Function Declaration

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.


A function declaration has the following parts:

return_type function_name( parameter list );


For our defined function add() in previous chapter, following is the function declaration:

int add(int a, int b);


Parameter names are not important in function declaration only their type is required, so following is also valid declaration:

int add(int, int);


Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.


Function Call

While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.


When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.


To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value.


For example:

int main ()

{

int a = 100;

int b = 200;

int ret;

// calling a function to get addition.

ret = add(a, b);

cout << "addition is : " << ret << endl;

return 0;

}


Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.


While calling a function, there are two ways that arguments can be passed to a function:

Call by value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.


Call by pointer

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.


Call by reference

This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.




7.3 Inline function


Calling a function generally causes a certain overhead (stacking arguments, jumps, etc...), and thus for very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function.


Preceding a function declaration with the inline specifier informs the compiler that inline expansion is preferred over the usual function call mechanism for a specific function. This does not change at all the behavior of a function, but is merely used to suggest the compiler that the code generated by the function body shall be inserted at each point the function is called, instead of being invoked with a regular function call.


For example, the concatenate function above may be declared inline as:

inline string concatenate (const string& a, const string& b)

{

return a+b;

}


This informs the compiler that when concatenate is called, the program prefers the function to be expanded inline, instead of performing a regular call. inline is only specified in the function declaration, not when it is called.


Note that most compilers already optimize code to generate inline functions when they see an opportunity to improve efficiency, even if not explicitly marked with the inline specifier. Therefore, this specifier merely indicates the compiler that inline is preferred for this function, although the compiler is free to not inline it, and optimize otherwise. In C++, optimization is a task delegated to the compiler, which is free to generate any code for as long as the resulting behavior is the one specified by the code.




7.4 Recursion


Recursion is a programming technique that allows the programmer to express operations in terms of themselves.


In C++, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process". This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes be completed without the recursive call.


void CountDown(int nValue)

{

using namespace std;

cout << nValue << endl;

CountDown(nValue-1);

}


int main(void)

{

CountDown(10);

return 0;

}


When CountDown(10) is called, the number 10 is printed, and CountDown(9) is called. CountDown(9) prints 9 and calls CountDown(8). CountDown(8) prints 8 and calls CountDown(7). The sequence of CountDown(n) calling CountDown(n-1) is continually repeated, effectively forming the recursive equivalent of an infinite loop.


This program illustrates the most important point about recursive functions: you must include a termination condition, or they will run “forever” (or until the call stack runs out of memory).

Stopping a recursive function generally involves using an if statement. Here is our function redesigned with a termination condition:


void CountDown(int nValue)

{

using namespace std;

cout << nValue << endl;


// termination condition

if (nValue > 0)

CountDown(nValue-1);

}


int main(void)

{

CountDown(10);

return 0;

}


Now when we run our program, CountDown() will count down to 0 and then stop!







Comments

Popular posts from this blog

How To install Kali Linux (nethunter) On Android (Without root) via proot-distro and install Kali Linux Xfce Desktop On Android using Termux

What is kali linux? Kali Linux is a Debian-derived Linux distribution designed for digital forensics and penetration testing. It is maintained and funded by Offensive Security , This tutorial isn't only about learning how to install Kali Linux. Okay let's run down what we will be doing                        Table Of Content •Installing Kali Linux Terminal •Installing Kali Linux Desktop •Installing Default packages  •Creating vncserver port •Closing vncserver port •Closing multiple vncserver ports  •Reseting Kali Linux •Uninstalling Kali Linux  Okay!!!! Let's Begin Requirements: • Termux  : Click Here To Download Termux   Installation:   Please you can also copy and paste the commands below    The First thing we have to do is to make sure our repositories are up to date, to do that type the command  pkg update   It is essent...

How To install Windows 10 in Termux(Without rooting your Android phone)

   Hello guys what's up, Today we are going to see how easily we can run Windows 10 Operating System on Android Phone just by running few commands on Termux and if you will like this post I will also show you how to run the Windows 8.1 and Kali Linux GUI(Without root) on Android using Termux only in an upcoming post so just comment down below if you are interested. This method is quite interesting as this will make you understand how powerful a Linux terminal can be so without wasting any more time let’s start this tutorial. Below you will find all the resources you need and their download links so Download all the files, install, and copy it to your smartphone's Internal or External Storage. Requirements: •ZArchiver : Click Here To Download ZArchiver • Termux  : Click Here To Download Termux • AVNC :  Click Here To Download AVNC • Windows 10 : Click Here To Download The Windows 10 File After download the windows 10 file you need to Install termux and AVNC server...

Geegpay Writing Challenge: The Story of Amina

  Geegpay Writing Challenge Prompt: Life throws us lemons, and sometimes it's hard to make lemonade out of them. Amina, a 25-year-old aspiring photographer, is struggling to make ends meet while juggling freelance gigs and caring for her ageing mother. She feels invisible, undervalued, and on the verge of giving up. But then, an unexpected encounter with a renowned artist reignites her passion and inspires her to take control of her own narrative. Write a 300-word short story from Amina's perspective, showing her journey from despair to determination. Write about the challenges she faces, the things she learns about herself and how she finds the strength to turn things around.     Life throws us lemons, and sometimes it's hard to make lemonade out of them. My Story Starts Here:   Amina was walking down a crowded street with a heavy bag of cameras on her shoulder and a lot on her mind. 25 years old, she was feeling crushed by the pressures of life. She was struggling...