C++ Function

C++ Functions

The function in C++ language is also known as procedure or subroutine in other programming languages.
To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.

Advantage of functions in C++

There are many advantages of functions.
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the same code again and again.
2) Code optimization
It makes the code optimized, we don't need to write much code.
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it several times.

Example:-


#include<iostream>
int max(int num1, int num2) {
   // local variable declaration
   int result;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}
int main()
{
int a=max(2,3); // call a function
cout<<a; // print max value
return 0;
}


1 comment:

  1. Hi There,


    Great piece on C++ Functions, I’m a fan of the ‘flowery’ style Looking forward to more long form articles ??

    I am using one dll in my application for including the functionality provided by that dll . This dll I am getting after installing one msi . But in my application I have a requirement like if the user has not installed that msi then we have to show one warning message(e.g msi has not installed , code for this I have implemented in the main() of my application ) and have to exit from the application .


    I look forward to see your next updates.


    Gracias,
    Uday

    ReplyDelete