• June 13, 2021

PHSARIT

Bring Technology Ideas with you

 What is a function in C++ programming language?

Function is a collection of code which is doing based on what we demand the code to do. The function consists of parameters and the return value.

Why do we need function? Functions are used to do certain actions, and they are important for re-implement the codes: use its code once, and use it many times.


return type/ data type function name (data type parameter)
	{
	 do something;
	}return value

The function the above is using the return type of data which mean that it must be declared while using in the main function of C++. As an example:

double Function_Plus(double x, double y)
{
	return x + y;
}

while using in main:

#include<iostream>
#include<string>
using namespace std;
int main()
{
	double x, y;
	cout << "Pleas enter x:" << endl;
	cin >> x;
	cout << "Please enter y:" << endl;
	cin >> y;
	double result = Function_Plus(x, y); // call function to use
	cout << "result is:" << result;
        system("pause==0");
}

See the result:

    result after compiling

    The other function which does not return the value, in C++ you need to use key word Void as the below:

    void function name ()
     {
     do something
     }
     

    The function the above can be used with parameters or not is up to you as below is an example of using Void function:

    void Log(const char * username, const char * password)
     {
    	 if (username == "admin")
    	 {
    		 if (password == "admin")
    		 {
    			 cout << "Login Succesfully"<<endl;
    		}
    		 else
    		 {
    			 cout << "Password is not correct" << endl;
    		 }
    	 }
    	 else
    	 {
    		 cout << "username is not correct"<<endl;
    	 }
     }

    While using in main function:

    #include<iostream>
    using namespace std;
    //create function login
    void Log(const char * username, const char * password)
     {
    	 if (username == "admin")
    	 {
    		 if (password == "admin")
    		 {
    			 cout << "Login Succesfully"<<endl;
    		}
    		 else
    		 {
    			 cout << "Password is not correct" << endl;
    		 }
    	 }
    	 else
    	 {
    		 cout << "username is not correct"<<endl;
    	 }
     }
    int main()
    {
    
    	Log("admin", "admin");
    	system("pause==0");
    }

    **key note: all functions must contain bracket (). Example: Login()

    Related post