What are functions in C and C++

As the name suggests, a function does some action, for example when you switch ON the light bulb, then that switch performs a particular action to turn on the Light Bulb. Similarily, Functions in programming is used to perform a specific task so as to save our time by writing the same logical code.

Why use a Function?

It is used where repeated task have to be done. It also makes your code neat and simple to understand. Many professional programmer advice to use Functions because it is the best practise for coding and debugging for any error. You should also prefer to use functions in your program. It divide your code, into simpler blocks, and thus reduces redundancy.

Functions are of two types:

  • Predefined Functions: These type of functions have been previously defined and they can be used by using Header files.For example, main() is a predefined, and compiler looks for it.
  • User-Defined Functions: These type of function are defined by the User, and used later in the program.

Working of Function :

Return Type : It tell us what data-type a particular function is going to give. Example, void, float, double, int , etc. Note that with void, you cannot use return.

Function Name : It is the unique name of the function. If more than one same name is defined in a program, then an error message will be thrown by the compiler. It could be any name.

Argument Name and Type : It tell us what type of value a function is going to take and how much arguments are needed to be passed through it. There is no limit in the number of argument.

Pass By Value: Here the actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. This ensures that any changes made inside function are not changed in actual parameters of calling function.

Pass By Reference : Here, both are referred to same address location, thus any change made inside function, also changes the actual parameters of calling function.

A simple example of Function :

Here a simple demonstration of function is given, along with explanation in form of comments.

using namespace std;

int sum ( int a , int b );      // Function Declaration

int main()
   int a , b ;
   cout << "Enter 2 numbers " << endl;
   cin >> a >> b;
   int c = sum (a,b);        // Function Calling with arguments passing
   cout << "Sum of two numbers:  "<< c;
   return 0; 

int sum ( int a , int b )     // Function Definition
     return a + b;


Enter 2 numbers

5 , 7

Sum of two numbers: 12

Facebook Comments

Show More

Leave a Reply

Back to top button