V tomto tutoriálu se pomocí příkladů dozvíme o funkci C ++ a jejích výrazech.
Funkce je blok kódu, který provádí konkrétní úkol.
Předpokládejme, že musíme vytvořit program, který vytvoří kruh a vybarví jej. K vyřešení tohoto problému můžeme vytvořit dvě funkce:
- funkce k nakreslení kruhu
- funkce pro vybarvení kruhu
Rozdělení složitého problému na menší bloky umožňuje náš program snadno pochopit a znovu použít.
Existují dva typy funkcí:
- Standardní funkce knihovny: Předdefinováno v C ++
- Uživatelem definovaná funkce: Vytvořeno uživateli
V tomto tutoriálu se zaměříme hlavně na uživatelem definované funkce.
C ++ uživatelsky definovaná funkce
C ++ umožňuje programátorovi definovat vlastní funkci.
Uživatelem definovaný kód skupiny funkcí pro provedení konkrétního úkolu a této skupině kódu je přidělen název (identifikátor).
Když je funkce vyvolána z kterékoli části programu, provede všechny kódy definované v těle funkce.
Deklarace funkce C ++
Syntaxe pro deklaraci funkce je:
returnType functionName (parameter1, parameter2,… ) ( // function body )
Zde je příklad deklarace funkce.
// function declaration void greet() ( cout << "Hello World"; )
Tady,
- název funkce je
greet()
- návratový typ funkce je
void
- prázdné závorky znamenají, že nemá žádné parametry
- tělo funkce je napsáno uvnitř
()
Poznámka: O tomto returnType
a parameters
později v tomto tutoriálu se dozvíme .
Volání funkce
Ve výše uvedeném programu jsme deklarovali funkci s názvem greet()
. Abychom tuto greet()
funkci mohli použít , musíme ji zavolat.
Tady je způsob, jak můžeme volat výše uvedenou greet()
funkci.
int main() ( // calling a function greet(); )
![](https://cdn.wiki-base.com/4717969/c_function_with_examples.png.webp)
Příklad 1: Zobrazení textu
#include using namespace std; // declaring a function void greet() ( cout << "Hello there!"; ) int main() ( // calling the function greet(); return 0; )
Výstup
Ahoj!
Funkční parametry
Jak bylo uvedeno výše, funkci lze deklarovat pomocí parametrů (argumentů). Parametr je hodnota, která je předána při deklaraci funkce.
Uvažujme například níže uvedenou funkci:
void printNum(int num) ( cout << num; )
Zde je int
proměnná num parametrem funkce.
Při volání funkce předáme hodnotu parametru funkce.
int main() ( int n = 7; // calling the function // n is passed to the function as argument printNum(n); return 0; )
Příklad 2: Funkce s parametry
// 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ýstup
Int číslo je 5 Dvojité číslo je 5,5
Ve výše uvedeném programu jsme použili funkci, která má jeden int
parametr a jeden double
parametr.
Poté předáme num1 a num2 jako argumenty. Tyto hodnoty jsou ukládány funkčními parametry n1 a n2.
![](https://cdn.wiki-base.com/4717969/c_function_with_examples_2.png.webp)
Poznámka: Typ argumentů předaných při volání funkce se musí shodovat s odpovídajícími parametry definovanými v deklaraci funkce.
Prohlášení o vrácení
Ve výše uvedených programech jsme v deklaraci funkce použili void. Například,
void displayNumber() ( // code )
To znamená, že funkce nevrací žádnou hodnotu.
Je také možné vrátit hodnotu z funkce. Z tohoto důvodu musíme returnType
během deklarace funkce zadat funkci.
Potom lze return
příkaz použít k vrácení hodnoty z funkce.
Například,
int add (int a, int b) ( return (a + b); )
Zde máme datový typ int
místo void
. To znamená, že funkce vrací int
hodnotu.
Kód return (a + b);
vrací součet dvou parametrů jako hodnotu funkce.
Příkaz return
označuje, že funkce skončila. Žádný kód po return
ukončení funkce se nespustí.
Příklad 3: Přidejte dvě čí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ýstup
100 + 78 = 178
Ve výše uvedeném programu se add()
funkce používá k nalezení součtu dvou čísel.
int
Předáme dva literály 100
a 78
při volání funkce.
Vrátíme vrácenou hodnotu funkce do proměnné součet a poté ji vytiskneme.
![](https://cdn.wiki-base.com/4717969/c_function_with_examples_3.png.webp)
Všimněte si, že součet je proměnná int
typu. Je to proto, že návratová hodnota add()
je int
typu.
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 programu se sqrt()
funkce knihovny používá k výpočtu druhé odmocniny čísla.
Deklarace funkce sqrt()
je definována v souboru cmath
záhlaví. Proto #include
k použití této sqrt()
funkce musíme použít kód .
Další informace najdete ve funkcích standardní knihovny C ++.