C++ from Basics to Mastery — Part 3
What is a function? Episode 1
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
In this article, let’s learn about functions.
A function is a block of code that performs a specific task. Functions improve the structure of a program, It increases code reusability and makes programs easier to understand.
A function consists of parameters, return values, and the function body. Parameters represent input values passed to a function, The return value is the value that the function returns as a result after performing its work. The function body is a block of code that defines what the function does.
#include <iostream>
int add(int a, int b) { //Function declaration and definition
return a + b; //function body
}
int main() {
int result = add(5, 3); //function call
std::cout << "5 + 3 = " << result << std::endl; //Result output
return 0;
}
In the code aboveaddA function called was declared and defined. addA function is a function that takes two integer parameters and returns their sum. mainIn the functionaddCall the function to get the result of adding 5 and 3resultSave it in a variable, An example of outputting the results is shown.
Let's look at the code in more detail. int add()A function was declared, as a parameterint aandint bwas declared. In the function body, it returns the value of adding a and b.returnThere is a door.
In other words, this function takes two integers as input and returns the sum.
int main()In the functionaddCall the function with 5 and 3 as input. The add function returns 8, which is the result of adding 5 and 3, and is stored in the result variable. int result = add (5, 3);say it differently int result = return a + bYou can think of it like this.
after thatstd::coutUse to output the result "5 + 3 = 8". Functions exist in various forms such as lambda functions, recursive functions, and overloading. In this article, we only looked at the most basic types of functions.