C++ How to Create Functions

In this C++ article, i want to show you How to Create Functions in C++, Functions are used to group codes for performing specific tasks. For defining a function first you need to write the return type of the function, after that you need to write the name of  the function. So the return type is just the data type of the value that function returns. so if your function returns an  integer you need to use the return_type as int, or if returns a float you need to use the return type as float. If our functions is not returning any value we need to use void.

 

 

 

Also you can check more articles on c++ programming language

1: C++ Introduction & Program Structure 

2: C++ Variables And Data Types 

3: C++ Getting User Input 

4: C++ If Else Statement 

5: C++ Short Hand If Else

6: C++ Switch Statement 

7: C++ Loops Complete Example

8: C++ Arrays And Multi Dimensional Array

 

 

 

So now let’s create our function in C++

 

 

 

Function Prototype 

If a user-defined function is defined after main() function, compiler will show error. It is because compiler is unaware of user-defined function, types of argument passed to function and return type.  in c++ function is prototype is declaration of function without its body. as in the above example we have used function prototype.

 

 

If you run the code this will be the result

 

 

 

 

This is the second way of creating functions in C++ .

 

 

So you can see in the above example we have created our function at the top, when you have created your function at the top, you do not need to use function prototype.

 

 

 

If you run the result will be the same.

 

 

 

 

Function Parameters and Return Type

As we have said the you can use parameters in function, also you can return a value in a function.

 

So you can see that in the above example, our functions is returning an integer value, and also i have given two parameters for my function, basically our function is returning the addition of two value based on user input.

 

 

If you run the code, this will be the result

 

 

 

Default Parameter

Also you can give default parameter to a function like this.

 

 

 

 

 

Also you can watch the complete video for C++ How to Create Functions

 

 

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Share via
Copy link
Powered by Social Snap
×