Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Void Return Type | Function Return Values Specification
C++ Functions

book
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:

cpp

main

copy
#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;
}
123456789101112131415161718192021
#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.

cpp

main

copy
#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
}
1234567891011121314151617
#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 }
question mark

Which of the following statements is true about a function with a void return type?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 4
We use cookies to make your experience better!
some-alt