Function, code का एक block है जो एक specific task perform करता है। Function, statements का एक set है जो input लेता है, कुछ specific calculation करता है और output Produce करता है,
कुछ commonly या repeatedly किए गए task को एक साथ रखा जाए और एक function बनाया जाए ताकि अलग-अलग input के लिए एक ही code को बार-बार लिखने के बजाय, हम function को call कर सकें।
Why do we need function :
- Code redundancy को कम करने में function helpful होते हैं। अगर Software में कई जगहों पर functionality की जाती है, तो एक ही code को बार-बार लिखने के बजाय, हम एक function बनाते हैं और इसे हर जगह call करते हैं।
- यह maintenance में भी मदद करता है क्योंकि यदि हम future में workforce में changes करते हैं तो हमें एक place पर बदलना होगा।
- Functions, code modular बनाते हैं। यदि code को functions में divide किया जाता है तो code को read करना और उसका use करना वास्तव में easy हो जाता है।
- Functions abstraction provide करते हैं। Example के लिए, हम उनके internal work के बारे में चिंता(worrying) किए बिना library functions का उपयोग कर सकते हैं।
Types of function:
There are two types of functions in C++.
1. Standard Library Function(Predefined in C++).
2. User-defined Function(Created by user).
In this tutorial we will focus at User-defined functions-
User-Defined Function:
C++ Programmers को self functions को defined करने की अनुमति देता है। एक User-defined function group code को एक specific work करने के लिए call करता है और code के उस group को एक name (identifier) दिया जाता है। जब program के किसी भी हिस्से से function को call किया जाता है, तो यह function के body में defined code execute करता है।
Function Declaration :
Function Declaration, Compilers को number of parameters के बारे में बताती है Functions, data-type के parameter लेता है, और functions के return type को वापस करता है। Function declaration में parameter name डालना function declaration में optional है, लेकिन उन्हें definition में रखना आवश्यक है। नीचे Function declaration का एक उदाहरण दिया गया है।
returnType functionName(parameter1,parametr2,...){ //function body }
Here is an example of function declaration
// function declaration
void greeting() {
cout << "Hello Warriors";
}
Here,
The name of function is greet()
The return type of function is void.
The empty parenthesis means doesn’t have any parameter.
The function body is written under the {}.
Calling a function :
ऊपर दिए गए Program में हमने greet() नाम का एक function declare किया है। greet() function का उपयोग करने के लिए, हमें इसे call करने की आवश्यकता है। यहां बताया गया है कि हम ऊपर दिए गए greet() function को कैसे call कर सकते हैं।
int main() { //calling a function greet(); }
Example : Print Hello word using function
#include<iostream> using namespace std; //declaring a function void greet(){ cout<<"Hello warriors"; } int main(){ // calling the function greet(); return 0; }