Min menu

Pages

VB

Functions in C++ | C Plus Plus


 Functions in C Plus Plus

Function Function ) It is a group of commands grouped in one place and executed when we call it.
In the previous lessons, we learned about many of the ready-made functions in C++ Which is used to deal with text and numbers.

In this lesson, we will learn functions in C++ , how to create new functions, and how to use them.

A function is a group of commands grouped in one place and executed when we call it. In the previous lessons, we learned about many of the ready-made functions in C ++ that are used to deal with texts and numbers. In this lesson we will learn how to create new functions and how to use them.

Examples of ready-made functions in C++

Names of some of the functions we used in the previous lessons.

                  length();
	insert();
	replace();
		fmax();
	floor();
  

Functions technology terms in C-Plus

Ready functions in C++ It is said to her Built-in Functions.
The functions that the programmer defines are called User-defined Functions.

Technical terms Built-in functions in C ++ are called built-in functions. The functions that the programmer defines are called User-defined Functions.

How to build functions in C++

When defining any function in C++ You have to follow the following procedure:

returnType functionName(Parameter List)
{
&nbsp &nbsp // Function Body
}

 returnType : Specifies the type that the function will return when it terminates or if it will not return any value.
 functionName : represents the name we give the function, by which we can call it.
 Parameter List : What is meant by parameters (setting parameters is optional).
 Function Body : It means the body of the function, and it means the commands that we put in the function.


return type returnType ) In the function can be any type of data contained in C++ int -  double -  bool -  string etc..).
It is possible to put a name for a specific class, and here the intent is that the function returns an object of this class (Don't worry, you'll learn this in later lessons.)

If the function does not return any value, the word must be placed in the  void place of the word returnType.

Examples of defining new functions in C++

In the following example, we have defined a function named myFunction, its type void, It contains only a print command.
Then we called it in the function  main() so that the print command placed in it is executed.

The first example is the definition of a function whose name is myFunction, its type void, It contains only a print command.

Main.cpp
                    #include <iostream>
	  
	  using namespace std;
	  
		  // When called, it prints the myFunction statement. Here we have defined a function named
	  void myFunction() {
	  cout << "My first function is called";
		  }
	  
	  int main()
		  {
		  // In order to execute the command placed in it myFunction() here we called the function
	  myFunction();
	  
	  return 0;
		  }
	

We will get the following result when running.

                    My first function is called
	

Here we define a function named greeting, When called, we pass a name to it, and it prints a welcome message for the name that was passed to it.

The second example defines a function whose name  isgreeting, When called, we pass a name to it, and it prints a welcome message for the name that was passed to it.

Main.cpp
                    #include <iostream>
	  
	  using namespace std;
	  
		  // When called, it prints the greeting statement. Here we have defined a function called
	  void greeting(string name)
		  {
	  cout << "Hello " << name << ", welcome to our company.";
		  }
	  
	  int main()
		  {
		  // to execute the command in greeting() here we have called the function
	  greeting("Mhamad");
	  
	  return 0;
		  }
	

We will get the following result when running.

                    Hello Mhamad, welcome to our company.
	

Here we define a function named getSum, When called, we pass two numbers to it, and it returns the product of their sum.

The third example is the definition of a function whose name is getSum, When called, we pass two numbers to it, and it returns the product of their sum.

Main.cpp
                    #include <iostream>
	  
	  using namespace std;
	  
		  // When called, we pass two numbers to it, and it returns the result of their sum, get_sum. Here we have defined a function named
	  int getSum(int a, int b)
		  {
	  return a + b;
		  }
	  
	  int main()
		  {
		  // x in the variable get_sum() here we have stored the result of numbers 3 and 5 that the function will return
	  int result = getSum(3, 7);
	  
		  // which will be equal to 10 result here we have shown the value of the variable
	  cout << "Result = " << result;
	  
	  return 0;
		  }
	

We will get the following result when running.

                    Result = 10
	

Give a default value for the parameters in C++

C++ It allows you to set default values ​​for the parameters, so when the function is called, you have the option to pass the parameter values ​​in place instead of being forced to.


C plus terms 

The default value we set for the parameter is Default Argument.

Technical terms The default value that we set for the parameter is called Default Argument.

In the following example, we have defined a function named printLanguage.
This function has only one parameter whose name  language has text  "English" as the default value.
All this function does when it is called is to print the parameter value language.

Note:  Since the parameter  language has a value by default, this means that you no longer have to pass a value to it when calling the function because it already has a value.

An example of giving a default value for the parameters in C++

Test.cpp
                    #include <iostream>
	  
	  using namespace std;
	  
		  // And you can not pass a value because it already has a value of language when it is called. You can pass a value to it in the place of the parameter printLanguage. Here we have defined a function named
	  void printLanguage(string language="English")
		  {
	  cout << "Your language is " << language << endl;
		  }
	  
	  int main()
		  {
		  // "English" and thus its value will remain language without passing the value of the parameter place printLanguage() here we called the function
	  printLanguage();
	  
		  // "Arabic" and thus its value will be language for parameter 'Arabic' with printLanguage() being passed here we called the function
	  printLanguage("Arabic");
	  
	  return 0;
		  }
	

We will get the following result when running.

                    Your language is English
	  Your language is Arabic
	

Whatch out

If the function has more than one parameter and you want to set a default value for only one of the parameters it has, you must put the parameters with default values ​​in the other.
If you don't, you will be forced to set default values ​​for all parameters after the first parameter to which you set a default value.

Whatch out If the function has more than one parameter and you want to set a default value for only one of the parameters it assigns, then the parameters that have default values ​​must be placed in the other. If not, you will be obliged to set default values ​​for all parameters found after the first parameter that has a default value.

Here we have given you several examples of mistakes that you may make when setting default values ​​so that you can learn how to avoid them.

See examples »

Where should functions be defined in C++

language translator C++ The code reads line by line with the commands placed on each line executed directly when the program is running.
For this reason, the function you want to call must always be previously defined so that you do not have a problem when you run the program.


In the following example, we put the function  myFunction() after the function we called it from.
The problem that will occur when running here is caused by the fact that the compiler will not know what it is  myFunction() since it was called before the compiler had already read it.

first example

Main.cpp
                    #include <iostream>
	  
	  using namespace std;
	  
	  int main()
		  {
		  // myFunction() Here we called the function
	  myFunction();
	  
	  return 0;
		  }
	  
		  // which contains only the print command myFunction Here we have defined the function
	  void myFunction()
		  {
	  cout << "My first function is called";
		  }
	

The following error will appear when running, which means that the compiler did not know what  myFunction you are trying to invoke in the eighth line.

main.cpp|8|error: 'myFunction' was not declared in this scope|


Solve the problem of not recognizing the function in C++

To solve the problem of not recognizing the function that occurred in the previous example, we have two options:

  • Keep the function  myFunction() where it is and state its definition Function Declartion ) Only at the beginning of the file, and this method is considered the most preferred.

  • Placing the function  myFunction() on top of the function  main() so that the compiler can read it and identify it and be able to call it in the function  main() after it.



In the following example, we keep the function  myFunction() in place and state its definition Function Declartion ) before it is called in the function main().
So there will be no problem when calling the function  myFunction() from the function  main() because the compiler will have knowledge that the function  myFunction() actually exists.

second example

Main.cpp
                    #include <iostream>
	  
	  using namespace std;
	  
		  // so that the compiler will recognize it and be able to use the myFunction function ( Declartion ) here we have put a definition
	  void myFunction();
	  
	  int main()
		  {
		  // myFunction() Here we called the function
	  myFunction();
	  
	  return 0;
		  }
	  
		  // In other words, define what will happen when the function myFunction ( body ) is called. Here we have defined a body
	  void myFunction()
		  {
	  cout << "My first function is called";
		  }
	

In the function, the function  main() will be called and the  function will be executedmyFunction() the function will be executed  without any problems and we will get the following result when running.

                    My first function is called
	

advice

It is always better to put definitions of functions Functions Declartions ) before the function main()  and define the content of these functions after it, because reading the code will become easier for you.

Advice It is always better to put the function definitions (Functions Declartions) before the main () function and define the contents of these functions after them as follows because reading the code will become easier for you.

The following example just shows you how to arrange the code if you intend to define many functions in the file.

third example

                    #include <iostream>
	  
	  using namespace std;
	  
		  // We state the definition of all the functions that we will create later in main() before the function
	  void printMessage();
	  void greeting(string name);
	  
		  // and in it we can call any function we mentioned earlier without any problems main() here we define the function
	  int main()
		  {
		  // greeting() and printMessage() here we can call
	  return 0;
		  }
	  
		  // Because we mentioned that it exists before printMessage() here we are defining the function
	  void printMessage()
		  {
		  // Here we write what will happen when it is called
		  }
	  
		  // Because we have mentioned that it exists before greeting() here we are defining the function
	  void greeting(string name)
		  {
		  // Here we write what will happen when it is called
		  }
	
______

Errors may appear due to setting default values ​​for parameters in C++

In all the examples, we will assume that we want to define a function and each time we try to pass default values ​​for some of its elements.


first example

In the following example we have given  c a default value and this will not cause a problem because there is no parameter after it.

                  void printMax(int a, int b, int c=0)
		{
	
		}
  


second example

The following example has a problem as we have given  b a default value and not given a default value for the parameter  c after it.
This will cause a problem when running the code.

                  void printMax(int a, int b=0, int c) 
		{
	
		}
  

This function will cause the following error in the code which means that the problem is forgetting to set a default value for the third parameter.

error: default argument missing for parameter 3 of 'void printMax(int, int, int)'


third example

In the following example we have given  b and  c default values ​​and this will not cause a problem because there are no parameters after them.

                  void printMax(int a, int b=0, int c=0) 
		{
	
		}
  


Fourth example

The following example has a problem as we have given  a a default value and not given a default value for the two parameters  b and  c those after it.
This will cause a problem when running the code.

                  void printMax(int a=0, int b, int c) 
		{
	
		}
  

This function will cause the following error in the code which means that the problem is forgetting to set a default value for the second and third parameters.

error: default argument missing for parameter 2 of 'void printMax(int, int, int)'
error: default argument missing for parameter 3 of 'void printMax(int, int, int)'


Fifth example

In the following example, we have given  a and  default values b ,  c ie all parameters, so there is no problem here.

                  void printMax(int a=0, int b=0, int c=0) 
		{
	
		}