V tej vadnici bomo s pomočjo primerov spoznali funkcijo C ++ in izraze funkcij.
Funkcija je blok kode, ki izvaja določeno nalogo.
Recimo, da moramo ustvariti program za ustvarjanje kroga in njegovo barvanje. Za rešitev te težave lahko ustvarimo dve funkciji:
- funkcija za risanje kroga
- funkcija za barvanje kroga
Če zapleteno težavo razdelimo na manjše dele, je naš program enostaven za razumevanje in ponovna uporaba.
Obstajata dve vrsti funkcij:
- Standardne funkcije knjižnice: vnaprej določene v jeziku C ++
- Uporabniško določena funkcija: ustvarili uporabniki
V tej vadnici se bomo osredotočili predvsem na uporabniško določene funkcije.
Uporabniško določena funkcija C ++
C ++ programerju omogoča, da sam določi svojo funkcijo.
Uporabniško definirana funkcija združuje kodo za izvajanje določene naloge in tej skupini kod se dodeli ime (identifikator).
Ko se funkcija prikliče iz katerega koli dela programa, se vse izvršijo kode, določene v telesu funkcije.
Izjava o funkciji C ++
Sintaksa za razglasitev funkcije je:
returnType functionName (parameter1, parameter2,… ) ( // function body )
Tu je primer izjave funkcije.
// function declaration void greet() ( cout << "Hello World"; )
Tukaj,
- ime funkcije je
greet()
- vrnjeni tip funkcije je
void
- prazne oklepaje pomenijo, da nima nobenih parametrov
- telo funkcije je zapisano znotraj
()
Opomba: V tej vadnici bomo izvedeli več o tem returnType
in parameters
kasneje.
Klicanje funkcije
V zgornjem programu smo razglasili funkcijo z imenom greet()
. Za uporabo greet()
funkcije jo moramo poklicati.
Evo, kako lahko pokličemo zgornjo greet()
funkcijo.
int main() ( // calling a function greet(); )
![](https://cdn.wiki-base.com/4717969/c_function_with_examples.png.webp)
Primer 1: Prikažite besedilo
#include using namespace std; // declaring a function void greet() ( cout << "Hello there!"; ) int main() ( // calling the function greet(); return 0; )
Izhod
Pozdravljeni!
Parametri funkcije
Kot smo že omenili, lahko funkcijo deklariramo s parametri (argumenti). Parameter je vrednost, ki se posreduje pri razglasitvi funkcije.
Oglejmo si na primer spodnjo funkcijo:
void printNum(int num) ( cout << num; )
Tu je int
spremenljivka num funkcijski parameter.
Med klicanjem funkcije parametru funkcije posredujemo vrednost.
int main() ( int n = 7; // calling the function // n is passed to the function as argument printNum(n); return 0; )
Primer 2: Funkcija s parametri
// program to print a text #include using namespace std; // display a number void displayNum(int n1, float n2) ( cout << "The int number is " << n1; cout << "The double number is " << n2; ) int main() ( int num1 = 5; double num2 = 5.5; // calling the function displayNum(num1, num2); return 0; )
Izhod
Int številka je 5 Dvojna številka je 5,5
V zgornjem programu smo uporabili funkcijo, ki ima en int
parameter in en double
parameter.
Nato kot argumenta posredujemo num1 in num2. Te vrednosti shranijo funkcijski parametri n1 oziroma n2.
![](https://cdn.wiki-base.com/4717969/c_function_with_examples_2.png.webp)
Opomba: Tip argumentov, posredovanih med klicanjem funkcije, se mora ujemati z ustreznimi parametri, definiranimi v izjavi funkcije.
Izjava o vrnitvi
V zgornjih programih smo v izjavi funkcije uporabili void. Na primer
void displayNumber() ( // code )
To pomeni, da funkcija ne vrne nobene vrednosti.
Mogoče je tudi vrniti vrednost iz funkcije. Za to moramo določiti returnType
funkcijo med deklaracijo funkcije.
Nato lahko return
stavek uporabimo za vrnitev vrednosti iz funkcije.
Na primer
int add (int a, int b) ( return (a + b); )
Tu imamo int
namesto tipa podatkov void
. To pomeni, da funkcija vrne int
vrednost.
Koda return (a + b);
vrne vsoto obeh parametrov kot vrednost funkcije.
return
Izjava pomeni, da je funkcija končalo. Koda v return
notranjosti funkcije se ne izvrši.
3. primer: dodajte dve številki
// program to add two numbers using a function #include using namespace std; // declaring a function int add(int a, int b) ( return (a + b); ) int main() ( int sum; // calling the function and storing // the returned value in sum sum = add(100, 78); cout << "100 + 78 = " << sum << endl; return 0; )
Izhod
100 + 78 = 178
V zgornjem programu se add()
funkcija uporablja za iskanje vsote dveh števil.
int
Podajamo dva dobesedna znaka 100
in 78
med klicanjem funkcije.
Vrnjeno vrednost funkcije shranimo v spremenljivko sum, nato pa jo natisnemo.
![](https://cdn.wiki-base.com/4717969/c_function_with_examples_3.png.webp)
Upoštevajte, da je vsota spremenljivka int
tipa. To je zato, ker je povratna vrednost add()
je int
tipa.
Prototip funkcije
In C++, the code of function declaration should be before the function call. However, if we want to define a function after the function call, we need to use the function prototype. For example,
// function prototype void add(int, int); int main() ( // calling the function before declaration. add(5, 3); return 0; ) // function definition void add(int a, int b) ( cout << (a + b); )
In the above code, the function prototype is:
void add(int, int);
This provides the compiler with information about the function name and its parameters. That's why we can use the code to call a function before the function has been defined.
The syntax of a function prototype is:
returnType functionName(dataType1, dataType2,… );
Example 4: C++ Function Prototype
// using function definition after main() function // function prototype is declared before main() #include using namespace std; // function prototype int add(int, int); int main() ( int sum; // calling the function and storing // the returned value in sum sum = add(100, 78); cout << "100 + 78 = " << sum << endl; return 0; ) // function definition int add(int a, int b) ( return (a + b); )
Output
100 + 78 = 178
The above program is nearly identical to Example 3. The only difference is that here, the function is defined after the function call.
That's why we have used a function prototype in this example.
Benefits of Using User-Defined Functions
- Functions make the code reusable. We can declare them once and use them multiple times.
- Functions make the program easier as each small task is divided into a function.
- Functions increase readability.
C++ Library Functions
Library functions are the built-in functions in C++ programming.
Programmers can use library functions by invoking the functions directly; they don't need to write the functions themselves.
Some common library functions in C++ are sqrt()
, abs()
, isdigit()
, etc.
In order to use library functions, we usually need to include the header file in which these library functions are defined.
For instance, in order to use mathematical functions such as sqrt()
and abs()
, we need to include the header file cmath
.
Example 5: C++ Program to Find the Square Root of a Number
#include #include using namespace std; int main() ( double number, squareRoot; number = 25.0; // sqrt() is a library function to calculate the square root squareRoot = sqrt(number); cout << "Square root of " << number << " = " << squareRoot; return 0; )
Output
Kvadratni koren 25 = 5
V tem programu se sqrt()
funkcija knjižnice uporablja za izračun kvadratnega korena števila.
Izjava funkcije sqrt()
je definirana v cmath
datoteki glave. Zato moramo uporabiti kodo #include
za uporabo sqrt()
funkcije.
Če želite izvedeti več, obiščite funkcije standardne knjižnice C ++.