Funkcia C ++ (s príkladmi)

V tomto tutoriále sa pomocou príkladov dozvieme o funkcii C ++ a výrazoch funkcií.

Funkcia je blok kódu, ktorý vykonáva konkrétnu úlohu.

Predpokladajme, že musíme vytvoriť program na vytvorenie kruhu a jeho vyfarbenie. Na vyriešenie tohto problému môžeme vytvoriť dve funkcie:

  • funkcia na nakreslenie kruhu
  • funkcia na vyfarbenie kruhu

Rozdelením zložitého problému na menšie časti je náš program ľahko pochopiteľný a opakovane použiteľný.

Existujú dva typy funkcií:

  1. Štandardné knižničné funkcie: Preddefinované v C ++
  2. Užívateľom definovaná funkcia: Vytvorené používateľmi

V tomto tutoriáli sa zameriame hlavne na používateľom definované funkcie.

C ++ Užívateľom definované funkcie

C ++ umožňuje programátorovi definovať vlastnú funkciu.

Používateľom definovaný kód skupiny funkcií na vykonanie konkrétnej úlohy a tejto skupine kódu je pridelený názov (identifikátor).

Keď je funkcia vyvolaná z ktorejkoľvek časti programu, vykoná všetky kódy definované v tele funkcie.

Deklarácia funkcií v C ++

Syntax na vyhlásenie funkcie je:

 returnType functionName (parameter1, parameter2,… ) ( // function body )

Tu je príklad deklarácie funkcie.

 // function declaration void greet() ( cout << "Hello World"; )

Tu,

  • názov funkcie je greet()
  • návratový typ funkcie je void
  • prázdne zátvorky znamenajú, že nemá žiadne parametre
  • telo funkcie je napísané vo vnútri ()

Poznámka: O tomto kurze sa dozvieme ďalej returnTypea parametersneskôr.

Volanie funkcie

Vo vyššie uvedenom programe sme deklarovali funkciu s názvom greet(). Aby greet()sme mohli funkciu používať , musíme ju zavolať.

Tu môžeme nazvať vyššie uvedenú greet()funkciu.

 int main() ( // calling a function greet(); )
Ako funguje funkcia v C ++

Príklad 1: Zobrazenie textu

 #include using namespace std; // declaring a function void greet() ( cout << "Hello there!"; ) int main() ( // calling the function greet(); return 0; )

Výkon

 Ahoj!

Parametre funkcie

Ako už bolo spomenuté vyššie, funkciu je možné deklarovať pomocou parametrov (argumentov). Parameter je hodnota, ktorá sa odovzdáva pri deklarovaní funkcie.

Zvážme napríklad nasledujúcu funkciu:

 void printNum(int num) ( cout << num; )

Tu je intpremenná num funkčným parametrom.

Pri volaní funkcie odovzdáme hodnotu funkčnému parametru.

 int main() ( int n = 7; // calling the function // n is passed to the function as argument printNum(n); return 0; )

Príklad 2: Funkcia s parametrami

 // 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; )

Výkon

 Int je číslo 5 Dvojité číslo je 5,5

Vo vyššie uvedenom programe sme použili funkciu, ktorá má jeden intparameter a jeden doubleparameter.

Potom odovzdáme čísla 1 a 1 ako argumenty. Tieto hodnoty sú uložené funkčnými parametrami n1 a n2.

Funkcia C ++ s parametrami

Poznámka: Typ argumentov odovzdaných pri volaní funkcie sa musí zhodovať s príslušnými parametrami definovanými v deklarácii funkcie.

Vyhlásenie o vrátení tovaru

Vo vyššie uvedených programoch sme vo vyhlásení funkcie použili void. Napríklad,

 void displayNumber() ( // code )

To znamená, že funkcia nevracia žiadnu hodnotu.

Je tiež možné vrátiť hodnotu z funkcie. Preto musíme returnTypepočas deklarácie funkcie špecifikovať funkciu.

Potom je možné returnpríkaz použiť na vrátenie hodnoty z funkcie.

Napríklad,

 int add (int a, int b) ( return (a + b); )

Tu máme dátový typ intnamiesto void. To znamená, že funkcia vráti inthodnotu.

Kód return (a + b);vráti súčet dvoch parametrov ako hodnotu funkcie.

Výrok returnoznačuje, že funkcia skončila. Žiadny kód po returnukončení funkcie sa nevykoná.

Príklad 3: Pridajte dve čísla

 // 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; )

Výkon

 100 + 78 = 178

Vo vyššie uvedenom programe sa add()funkcia používa na nájdenie súčtu dvoch čísel.

intMíňame dva literály 100a 78pri volaní funkcie.

Vrátenú hodnotu funkcie uložíme do premennej súčet a potom ju vytlačíme.

Fungovanie funkcie C ++ s návratovým príkazom

Všimnite si, že súčet je premennou inttypu. Je to preto, že návratová hodnota parametra add()je inttypu.

Funkčný prototyp

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

 Druhá odmocnina z 25 = 5

V tomto programe sa sqrt()funkcia knižnice používa na výpočet druhej odmocniny čísla.

Deklarácia funkcie sqrt()je definovaná v cmathhlavičkovom súbore. Preto #include na použitie sqrt()funkcie musíme použiť kód .

Ak sa chcete dozvedieť viac, navštívte funkcie štandardnej knižnice C ++.

Zaujímavé články...