Function type

Function type

Function type

In C++, functions can have various types depending on their return value and arguments. Here are the main function type in C++:

Functions with a void return type: These functions do not return any value. They are typically used for performing operations that do not need to return a value to the caller.

				
					void sayHello() {

    std::cout << "Hello!"<< std::endl;

}
​
				
			
  1. Functions with a non-void return type: These functions return a value of a specified type to the caller. For example, the following function returns an integer value:
				
					int add(int a, int b) {

    return a + b;

}
​
				
			

Functions with no arguments: These functions do not take any arguments. For example:

				
					void printMessage() {

    std::cout << "This is a message." << std::endl;

}
​
				
			

Functions with one or more arguments: These functions take one or more arguments of specified types. For example:

				
					void printName(std::string name) {

    std::cout << "Your name is:" << name << std::endl;

}
​
				
			

Note that functions can also be declared as const or static, among other modifiers. const functions promise not to modify the state of the object, while static functions are not tied to a specific instance of a class.

  1. Functions that return a pointer: These functions return a memory address that points to a variable or object. For example:
				
					int* createIntArray(int size) {

    return new int[size];

}
​
				
			

In this example, the function createIntArray takes an integer argument size and returns a pointer to a dynamically allocated array of integers.

  1. Functions that return a reference: These functions return a reference to a variable or object. For example:
				
					int& getLargest(int* arr, int size) {

    int largest = arr[0];

    for (int i = 1; i < size; i++) {

        if (arr[i] > largest) {

            largest = arr[i];

        }

    }

    return largest;

}

​
				
			

In this example, the function getLargest takes an array of integers arr and its size size as arguments, and returns a reference to the largest element in the array.

 

Note that the return type of a function must match the type of the value that the function returns.

Join To Get Our Newsletter
Spread the love