Sunday, February 1, 2026

C++ Functions - Syntax, Categories and Examples

What is a Function? 
  • A function in C++ is a block of code that performs a specific task. 

Key Benefits:
  • It helps in breaking a large program into smaller, manageable parts, improves code reusability, and makes programs easy to understand and maintain.
General Syntax of a Function

return_type function_name(parameter_list)
{

  // function body
  // statements

  return value; // optional (if return_type is void)
}

Key points
  • return_type: Data type of the value returned by the function (e.g., int, float, void)

  • function_name: Name of the function (should be meaningful)

  • parameter_list: Input values passed to the function (optional)

  • function body: Contains the logic of the function

  • return statement: Sends the result back to the calling function

Categories of Functions - Examples:

Example 1: Function without Parameters and without Return Value

#include <iostream>
using namespace std;
void greet()
{
  cout << "Welcome to C++ Programming";
}
int main()
{
  greet();
  return 0;
}

Key Points: The function greet() simply prints a message. It does not take inputs or return any value.

Example 2: Function with Parameters and without Return Value

#include <iostream>
using namespace std;
void add(int a, int b)
{
  cout << "Sum = " << a + b;
}
int main()
{
  add(10, 20);
  return 0;
}

Key points: The function add() receives two integers and displays their sum.

Example 3: Function with Parameters and Return Value

#include <iostream>
using namespace std;
int square(int n)
{
  return n * n;
}
int main()
{
  int result = square(5);
  cout << "Square = " << result;
  return 0;
}

Key points: The function square() calculates and returns the square of a number.

Example 4: Function without Parameters but with Return Value

#include <iostream>
using namespace std;
int getNumber()
{
  return 100;
}
int main()
{
  cout << "Number = " << getNumber();
  return 0;
}

Key points: The function getNumber() returns a fixed integer value.


* * * * *