C++ Functions

In this tutorial, we will learn about the C++ function and function expressions with the help of examples.

A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it. We can create two functions to solve this problem:

  • a function to draw the circle
  • a function to color the circle

Dividing a complex problem into smaller chunks makes our program easy to understand and reusable.

There are two types of function:

  1. Standard Library Functions: Predefined in C++
  2. User-defined Function: Created by users

In this tutorial, we will focus mostly on user-defined functions.


C++ User-defined Function

C++ allows the programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code is given a name (identifier).

When the function is invoked from any part of the program, it all executes the codes defined in the body of the function.


C++ Function Declaration

The syntax to declare a function is:

returnType functionName (parameter1, parameter2,...) {
    // function body   
}

Here’s an example of a function declaration.
 

// function declaration
void greet() {
    cout << "Hello World";
}

Here,

  • the name of the function is greet()
  • the return type of the function is void
  • the empty parentheses mean it doesn’t have any parameters
  • the function body is written inside {}

Note: We will learn about returnType and parameters later in this tutorial.


Calling a Function

In the above program, we have declared a function named greet(). To use the greet() function, we need to call it.

Here’s how we can call the above greet() function.

int main() {
     
    // calling a function   
    greet(); 

}
Working of C++ function
How Function works in C++

Example 1: Display a Text

#include <iostream>
using namespace std;

// declaring a function
void greet() {
    cout << "Hello there!";
}

int main() {

    // calling the function
    greet();

    return 0;
}

Run Code

Output

Hello there!

Function Parameters

As mentioned above, a function can be declared with parameters (arguments). A parameter is a value that is passed when declaring a function.

For example, let us consider the function below:

void printNum(int num) {
    cout << num;
}

Here, the int variable num is the function parameter.

We pass a value to the function parameter while calling the function.

int main() {
    int n = 7;
    
    // calling the function
    // n is passed to the function as argument
    printNum(n);
    
    return 0;
}

Example 2: Function with Parameters

// program to print a text

#include <iostream>
using namespace std;

// display a number
void displayNum(int n1, float n2) {
    cout << "The int number is " << n1;
    cout << "The double number is " << n2;
}

int main() {
     
     int num1 = 5;
     double num2 = 5.5;

    // calling the function
    displayNum(num1, num2);

    return 0;
}

Run Code

Output

The int number is 5
The double number is 5.5

In the above program, we have used a function that has one int parameter and one double parameter.

We then pass num1 and num2 as arguments. These values are stored by the function parameters n1 and n2 respectively.

C++ function with parameters
C++ function with parameters

Note: The type of the arguments passed while calling the function must match with the corresponding parameters defined in the function declaration.


Return Statement

In the above programs, we have used void in the function declaration. For example,

void displayNumber() {
    // code
}

This means the function is not returning any value.

It’s also possible to return a value from a function. For this, we need to specify the returnType of the function during function declaration.

Then, the return statement can be used to return a value from a function.

For example,

int add (int a, int b) {
   return (a + b);
}

Here, we have the data type int instead of void. This means that the function returns an int value.

The code return (a + b); returns the sum of the two parameters as the function value.

The return statement denotes that the function has ended. Any code after return inside the function is not executed.


Example 3: Add Two Numbers

// program to add two numbers using a function

#include <iostream>

using namespace std;

// declaring a function
int add(int a, int b) {
    return (a + b);
}

int main() {

    int sum;
    
    // calling the function and storing
    // the returned value in sum
    sum = add(100, 78);

    cout << "100 + 78 = " << sum << endl;

    return 0;
}

Run Code

Output

100 + 78 = 178

In the above program, the add() function is used to find the sum of two numbers.

We pass two int literals 100 and 78 while calling the function.

We store the returned value of the function in the variable sum, and then we print it.

Working of C++ Function with return statement
Working of C++ Function with return statement

Notice that sum is a variable of int type. This is because the return value of add() is of int type.


Function Prototype

In C++, the code of function declaration should be before the function call. However, if we want to define a function after the function call, we need to use the function prototype. For example,

// function prototype
void add(int, int);

int main() {
    // calling the function before declaration.
    add(5, 3);
    return 0;
}

// function definition
add(int a, int b) {
    cout < (a + n);
}

In the above code, the function prototype is:

void add(int, int);

This provides the compiler with information about the function name and its parameters. That’s why we can use the code to call a function before the function has been defined.

The syntax of a function prototype is:

returnType functionName(dataType1, dataType2, ...);

Example 4: C++ Function Prototype

// using function definition after main() function
// function prototype is declared before main()

#include <iostream>

using namespace std;

// function prototype
int add(int, int);

int main() {
    int sum;

    // calling the function and storing
    // the returned value in sum
    sum = add(100, 78);

    cout << "100 + 78 = " << sum << endl;

    return 0;
}

// function definition
int add(int a, int b) {
    return (a + b);
}

Run Code

Output

100 + 78 = 178

The above program is nearly identical to Example 3. The only difference is that here, the function is defined after the function call.

That’s why we have used a function prototype in this example.


Benefits of Using User-Defined Functions

  • Functions make the code reusable. We can declare them once and use them multiple times.
  • Functions make the program easier as each small task is divided into a function.
  • Functions increase readability.

C++ Library Functions

Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly; they don’t need to write the functions themselves.

Some common library functions in C++ are sqrt()abs()isdigit(), etc.

In order to use library functions, we usually need to include the header file in which these library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the header file cmath.


Example 5: C++ Program to Find the Square Root of a Number

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double number, squareRoot;
    
    number = 25.0;

    // sqrt() is a library function to calculate the square root
    squareRoot = sqrt(number);

    cout << "Square root of " << number << " = " << squareRoot;

    return 0;
}

Run Code

Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root of a number.

The function declaration of sqrt() is defined in the cmath header file. That’s why we need to use the code #include <cmath> to use the sqrt() function.

To learn more, visit C++ Standard Library functions.

C goto statement

In this tutorial, you will learn to create the goto statement in C programming. Also, you will learn when to use a goto statement and when not to use it.

The goto statement allows us to transfer control of the program to the specified label.


Syntax of goto Statement

goto label;
... .. ...
... .. ...
label: 
statement;

The label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.

How goto statement works?

Example: goto Statement

// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.

#include <stdio.h>

int main() {

   const int maxInput = 100;
   int i;
   double number, average, sum = 0.0;

   for (i = 1; i <= maxInput; ++i) {
      printf("%d. Enter a number: ", i);
      scanf("%lf", &number);
      
      // go to jump if the user enters a negative number
      if (number < 0.0) {
         goto jump;
      }
      sum += number;
   }

jump:
   average = sum / (i - 1);
   printf("Sum = %.2f\n", sum);
   printf("Average = %.2f", average);

   return 0;
}

Output

1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53

Reasons to avoid goto

The use of goto statement may lead to code that is buggy and hard to follow. For example,

one:
for (i = 0; i < number; ++i)
{
    test += i;
    goto two;
}
two: 
if (test > 5) {
  goto three;
}
... .. ...

Also, the goto statement allows you to do bad stuff such as jump out of the scope.

That being said, goto can be useful sometimes. For example: to break from nested loops.


Should you use goto?

If you think the use of goto statement simplifies your program, you can use it. That being said, goto is rarely useful and you can create any C program without using goto altogether.

Here’s a quote from Bjarne Stroustrup, creator of C++, “The fact that ‘goto’ can do anything is exactly why we don’t use it.”

C functions

In this tutorial, you will be introduced to functions (both user-defined and standard library functions) in C programming. Also, you will learn why functions are used in programming.

A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can create two functions to solve this problem:

  • create a circle function
  • create a color function

Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.


Types of function

There are two types of function in C programming:


Standard library functions

The standard library functions are built-in functions in C programming.

These functions are defined in header files. For example,

  • The printf() is a standard library function to send formatted output to the screen (display output on the screen). This function is defined in the stdio.h header file.
    Hence, to use the printf()function, we need to include the stdio.h header file using #include <stdio.h>.
  • The sqrt() function calculates the square root of a number. The function is defined in the math.h header file.  

Visit standard library functions in C programming to learn more.


User-defined function

You can also create functions as per your need. Such functions created by the user are known as user-defined functions.

How user-defined function works?

#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}

int main()
{
... .. ...
... .. ...

functionName();

... .. ...
... .. ...
}

The execution of a C program begins from the main() function.

When the compiler encounters functionName();, control of the program jumps to

 void functionName()

And, the compiler starts executing the codes inside functionName().null

The control of the program jumps back to the main() function once code inside the function definition is executed.

How function works in C programming?

Note, function names are identifiers and should be unique.

This is just an overview of user-defined functions. Visit these pages to learn more on:

  • User-defined Function in C programming
  • Types of user-defined Functions

Advantages of user-defined function

  1. The program will be easier to understand, maintain and debug.
  2. Reusable codes that can be used in other programs
  3. A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.

C# Functions

Function is a block of code that has a signature. Function is used to execute statements specified in the code block. A function consists of the following components:

Function name: It is a unique name that is used to make Function call.

Return type: It is used to specify the data type of function return value.

Body: It is a block that contains executable statements.

Access specifier: It is used to specify function accessibility in the application.

Parameters: It is a list of arguments that we can pass to the function during call.

C# Function Syntax

FunctionName()
{
// function body
// return statement
}
	
	

Access-specifier, parameters and return statement are optional.

Let’s see an example in which we have created a function that returns a string value and takes a string parameter.

C# Function: using no parameter and return type

A function that does not return any value specifies void type as a return type. In the following example, a function is created without return type.

using System;
namespace FunctionExample
{
class Program
{
// User defined function without return type
public void Show() // No Parameter
{
Console.WriteLine(“Function Call without parameter”);
// No return statement
}

// Execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show(); // Calling Function
}
}
}

output:

Function Call without parameter

C# Function: using parameter but no return type

using System;
namespace FunctionExample
{
class Program
{
// User defined function without return type
public void Show(string message)
{
Console.WriteLine(“Hello ” + message);
// No return statement
}

// Execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show(“Students”); // Calling Function
}
}
}
Output:
Hello Students

C# Function: using parameter and return type

using System;
namespace FunctionExample
{
class Program
{
// User defined function
public string Show(string message)
{
Console.WriteLine(“Inside Show Function”);
return message;
}

// Execution entry point of the program
static void Main(string[] args)
{
Program program = new Program();
string message = program.Show(“Students”);
Console.WriteLine(“Hello “+message);
}
}
}
Output:
Inside Show Function
Hello Students