Functions

  • In the C programming language, functions are blocks of code that perform specific tasks or operations. Functions allow you to break down a program into smaller, more manageable parts, making the code more modular and easier to maintain.
  • When we need to do that task, we call it in main function because we know that in our C++ code, execution starts from main function and ends when main function ends.

Main Function

Declaring a Function

In this example;

  • return type shows the data type of value, function is returning.
  • funcName is the name of function. We can give any name to the function with some exceptions.
  • (params) are the parameters which we pass to function
  • Body of the function is written inside curly braces.

Defining a void Function

Void functions do not return anything. We just print anything we want inside void functions.

Calling a void Function inside main function

To see the results of a function, we need to call it in our main function. To call a function in main function, we write the name of the function, followed by parenthesis.

Functions which return a value

We can have functions which return some value. We can store this value in a variable or we can directly print it on screen.

Function Parameters and Arguments

  • Function parameters are variables, which we pass to function to perform an operation.
  • Arguments are the data values which we pass in parenthesis when we call a function.

Passing Arguments by Reference

Passing arguments by reference means that we will not pass variable's values. We will pass reference to variables. When we want to pass values by reference, we use pointers.

Passing Arrays as Arguments

We can also pass an array as an argument to a function.

Recursion

Recursion means calling the method within the same method. This is done to break the one complicated problem into many simpler problems and then solving the simpler problems.

Function Overloading

Function overloading allows us to define different functions with the same name but,

  • Overloading functions must have parameters with different data types, OR
  • Number of parameters must be different, OR
  • If number of parameters is same, their sequence must be different.

Return type of overloading functions may or may not be different.

Funtions with atleast one feature given above or having all the three features are said to be overloaded. When function is called, compiler determines which version of function to invoke.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

What is the return type of a function that doesn't return any value?

10 XP~2 min
Exercise 2 of 2Medium

A function that calls itself is called a ___ function.

15 XP~3 min