Funkcja C ++ (z przykładami)

W tym samouczku nauczymy się funkcji C ++ i wyrażeń funkcyjnych na przykładach.

Funkcja to blok kodu, który wykonuje określone zadanie.

Załóżmy, że musimy stworzyć program, który utworzy okrąg i pokoloruje go. Aby rozwiązać ten problem, możemy stworzyć dwie funkcje:

  • funkcja rysowania koła
  • funkcja do pokolorowania koła

Dzielenie złożonego problemu na mniejsze części sprawia, że ​​nasz program jest łatwy do zrozumienia i można go ponownie używać.

Istnieją dwa rodzaje funkcji:

  1. Standardowe funkcje biblioteki: wstępnie zdefiniowane w C ++
  2. Funkcja zdefiniowana przez użytkownika : utworzona przez użytkowników

W tym samouczku skupimy się głównie na funkcjach zdefiniowanych przez użytkownika.

Funkcja zdefiniowana przez użytkownika w C ++

C ++ pozwala programiście zdefiniować własną funkcję.

Zdefiniowany przez użytkownika kod grup funkcyjnych do wykonania określonego zadania i ta grupa kodu otrzymuje nazwę (identyfikator).

Gdy funkcja jest wywoływana z dowolnej części programu, wszystko to wykonuje kody zdefiniowane w treści funkcji.

Deklaracja funkcji C ++

Składnia deklarowania funkcji jest następująca:

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

Oto przykład deklaracji funkcji.

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

Tutaj,

  • nazwa funkcji to greet()
  • zwracanym typem funkcji jest void
  • puste nawiasy oznaczają, że nie ma żadnych parametrów
  • treść funkcji jest zapisana wewnątrz ()

Uwaga: dowiemy się o tym returnTypei parameterspóźniej w tym samouczku.

Wywołanie funkcji

W powyższym programie zadeklarowaliśmy funkcję o nazwie greet(). Aby użyć tej greet()funkcji, musimy ją wywołać.

Oto jak możemy wywołać powyższą greet()funkcję.

 int main() ( // calling a function greet(); )
Jak funkcja działa w C ++

Przykład 1: Wyświetl tekst

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

Wynik

 Witam!

Parametry funkcji

Jak wspomniano powyżej, funkcję można zadeklarować za pomocą parametrów (argumentów). Parametr to wartość, która jest przekazywana podczas deklarowania funkcji.

Na przykład rozważmy poniższą funkcję:

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

Tutaj intzmienna num jest parametrem funkcji.

Podczas wywoływania funkcji przekazujemy wartość do parametru funkcji.

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

Przykład 2: Funkcja z 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; )

Wynik

 Liczba int to 5 Podwójna liczba to 5,5

W powyższym programie użyliśmy funkcji, która ma jeden intparametr i jeden doubleparametr.

Następnie przekazujemy argumenty num1 i num2. Wartości te są przechowywane odpowiednio przez parametry funkcji n1 i n2.

Funkcja C ++ z parametrami

Uwaga: Typ argumentów przekazanych podczas wywoływania funkcji musi być zgodny z odpowiednimi parametrami zdefiniowanymi w deklaracji funkcji.

Instrukcja zwrotu

W powyższych programach użyliśmy void w deklaracji funkcji. Na przykład,

 void displayNumber() ( // code )

Oznacza to, że funkcja nie zwraca żadnej wartości.

Możliwe jest również zwrócenie wartości z funkcji. W tym celu musimy określić returnTypefunkcję podczas deklaracji funkcji.

Następnie returninstrukcja może służyć do zwracania wartości z funkcji.

Na przykład,

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

Tutaj mamy typ danych intzamiast void. Oznacza to, że funkcja zwraca intwartość.

Kod return (a + b);zwraca sumę dwóch parametrów jako wartość funkcji.

returnStwierdzenie oznacza, że funkcja została zakończona. Żaden kod znajdujący się po returnwnętrzu funkcji nie jest wykonywany.

Przykład 3: Dodaj dwie liczby

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

Wynik

 100 + 78 = 178

W powyższym programie add()funkcja służy do znalezienia sumy dwóch liczb.

Przekazujemy dwa intliterały 100i 78podczas wywoływania funkcji.

Zwracaną wartość funkcji przechowujemy w zmiennej sumie, a następnie ją drukujemy.

Działanie funkcji C ++ z instrukcją return

Zwróć uwagę, że suma jest zmienną inttypu. Dzieje się tak, ponieważ zwracana wartość add()jest inttypu.

Prototyp funkcji

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

 Pierwiastek kwadratowy z 25 = 5

W tym programie sqrt()funkcja biblioteki służy do obliczania pierwiastka kwadratowego z liczby.

Deklaracja funkcji sqrt()jest zdefiniowana w cmathpliku nagłówkowym. Dlatego musimy użyć kodu, #include aby użyć sqrt()funkcji.

Aby dowiedzieć się więcej, odwiedź stronę Funkcje biblioteki standardowej języka C ++.

Interesujące artykuły...