Functions अलग-अलग programs को करने के लिए code segments में programs की structure करने की अनुमति देते हैं। C ++ में, एक functions, statements का एक group है जिसे नाम दिया गया है, और जिसे program के किसी point से बुलाया जा सकता है। किसी function को declare करने के लिए general syntax है
Syntax of Function
Function type Function name( parameter1, parameter2,...) { statement }
where :
Function type : function का return type(function किस datatype की value return कर रहा है ) है।
Function name : Function name, identifier है जिसके द्वारा function को call किया जा सकता है।
Parameter(as needed as) : प्रत्येक parameter एक type consist करता है जो identifier द्वारा follow होता है, प्रत्येक parameter को semi द्वारा separated किया जाता है। प्रत्येक parameter एक regular variable declaration की तरह दिखता है
(उदाहरण के लिए: int x), और वास्तव में function के भीतर एक regular variable के रूप में कार्य करता है जो function के लिए local है। function का purpose, parameters को उस स्थान से argument pass करने की अनुमति देना है जहां से इसे called किया जाता है।
Statement :
Statement function का body है। यह braces {} से surrounded statements का एक block है जो specify करता है कि functions वास्तव में क्या करता है
// function example
#include <iostream>
using namespace std;
int add (int a, int b)
{
int c;
c=a+b;
return c;
}
int main ()
{
int c;
c = addition (5,3);
cout << "The result is " << c;
}
यह Program दो functions में बांटा गया है: addition और main । याद रखें कि जिस order में उन्हें declare किया गया है, कोई फर्क नहीं पड़ता, एक C++ program हमेशा main function को call करके शुरू होता है।
वास्तव में, Main एकमात्र function है जिसे automatically called किया जाता है, और किसी other functions में code केवल तभी execute होता है जब इसके function को main function से call किया (directly or indirectly रूप से) जाता है।
Above example में, main function int c नाम के variable को declare करके शुरू होता है, और उसके ठीक बाद, यह first function call करता है:
यह addition function को call करता है। किसी function के लिए call इसकी declaration के समान structure का पालन करता है। ऊपर दिए गए example में, call to addition की तुलना इसकी declaration से कुछ ही पंक्तियों में की जा सकती है: