Course Content
C++ Functions
C++ Functions
Void Return Type
In C++, the void
return type is used in functions to indicate that the function does not return any value. When a function has a void
return type, it means the function does its task without producing a result that needs to be used elsewhere in the program.
For example, let's consider the function that prints values of 1D dynamic array that we used before:
main
#include <iostream> // Function to print values of a 1D dynamic array void printArray(const int* arr, const int size) { for (int i = 0; i < size; ++i) std::cout << arr[i] << " "; std::cout << std::endl; } int main() { // Example 1D dynamic array int size = 5; int* dynamicArray = new int[size] { 1, 2, 3, 4, 5 }; // Call the function to print the array values printArray(dynamicArray, size); // Deallocate the dynamically allocated memory delete[] dynamicArray; }
We can see that the purpose of this function is to print the array, and it doesn't produce any meaningful result that must be returned. So we can use void
return value in this case.
But you can still use return
in a void function. For example if you want to terminate it on certain condition.
main
#include <iostream> void displayDivision(double a, double b) { if (b == 0) return; std::cout << "displayDivision was called: " << a / b << std::endl; } int main() { // Call the function to print the division result displayDivision(15, 8); // Now second argument is zero displayDivision(15, 0); // nothing happens }
Thanks for your feedback!