Coming Soon

This lesson is currently being developed

Void functions (non-value returning functions)

Learn about functions that perform actions without returning values.

C++ Basics: Functions and Files
Chapter
Beginner
Difficulty
35min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

2.3 — Void functions (non-value returning functions)

In this lesson, you'll learn about void functions - functions that perform actions but don't return a value to the caller.

What are void functions?

A void function is a function that performs a task but doesn't return a value. The keyword void means "nothing" or "no value." These functions are also called non-value returning functions.

void function_name(parameters)
{
    // perform some action
    // no return statement needed (or return; with no value)
}

Void functions are perfect for tasks like:

  • Displaying information to the user
  • Modifying global variables
  • Performing calculations without needing to send results back
  • Organizing code into logical chunks

Basic void function example

#include <iostream>

void sayHello()
{
    std::cout << "Hello, World!" << std::endl;
}

int main()
{
    sayHello();  // Call the function
    sayHello();  // Call it again
    
    return 0;
}

Output:

Hello, World!
Hello, World!

Notice that:

  • The function has void as its return type
  • There's no return statement with a value
  • We call the function but don't assign its result to anything

Void functions with parameters

Void functions can accept parameters to customize their behavior:

#include <iostream>

void greetUser(std::string name)
{
    std::cout << "Hello, " << name << "! Welcome to C++." << std::endl;
}

void printRectangle(int width, int height, char symbol)
{
    for (int row = 0; row < height; ++row)
    {
        for (int col = 0; col < width; ++col)
        {
            std::cout << symbol;
        }
        std::cout << std::endl;
    }
}

int main()
{
    greetUser("Alice");
    greetUser("Bob");
    
    std::cout << std::endl;
    printRectangle(5, 3, '*');
    
    return 0;
}

Output:

Hello, Alice! Welcome to C++.
Hello, Bob! Welcome to C++.

*****
*****
*****

The return statement in void functions

Void functions can use return statements, but they cannot return a value:

#include <iostream>

void checkAge(int age)
{
    if (age < 0)
    {
        std::cout << "Invalid age!" << std::endl;
        return;  // Exit the function early
    }
    
    if (age < 13)
        std::cout << "You are a child." << std::endl;
    else if (age < 20)
        std::cout << "You are a teenager." << std::endl;
    else
        std::cout << "You are an adult." << std::endl;
}

int main()
{
    checkAge(-5);   // Will exit early
    checkAge(10);   // Will complete normally
    checkAge(25);   // Will complete normally
    
    return 0;
}

Output:

Invalid age!
You are a child.
You are an adult.

The return; statement (with no value) immediately exits the function, which is useful for error handling or early termination.

Practical examples of void functions

1. Menu display function

#include <iostream>

void showMenu()
{
    std::cout << "=== MAIN MENU ===" << std::endl;
    std::cout << "1. Start Game" << std::endl;
    std::cout << "2. Load Save" << std::endl;
    std::cout << "3. Settings" << std::endl;
    std::cout << "4. Exit" << std::endl;
    std::cout << "Choose an option: ";
}

int main()
{
    showMenu();
    // Get user input here...
    
    return 0;
}

2. Mathematical operations display

#include <iostream>

void printMultiplicationTable(int number, int limit)
{
    std::cout << "Multiplication table for " << number << ":" << std::endl;
    
    for (int i = 1; i <= limit; ++i)
    {
        std::cout << number << " x " << i << " = " << (number * i) << std::endl;
    }
}

int main()
{
    printMultiplicationTable(7, 5);
    
    return 0;
}

Output:

Multiplication table for 7:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

3. Input validation and processing

#include <iostream>

void processGrade(double grade)
{
    std::cout << "Processing grade: " << grade << std::endl;
    
    if (grade < 0 || grade > 100)
    {
        std::cout << "Error: Grade must be between 0 and 100!" << std::endl;
        return;
    }
    
    std::cout << "Grade: " << grade << "% - ";
    
    if (grade >= 90)
        std::cout << "Excellent (A)" << std::endl;
    else if (grade >= 80)
        std::cout << "Good (B)" << std::endl;
    else if (grade >= 70)
        std::cout << "Satisfactory (C)" << std::endl;
    else if (grade >= 60)
        std::cout << "Needs Improvement (D)" << std::endl;
    else
        std::cout << "Failing (F)" << std::endl;
}

int main()
{
    processGrade(95.0);
    processGrade(67.0);
    processGrade(105.0);  // Invalid grade
    
    return 0;
}

Output:

Processing grade: 95
Grade: 95% - Excellent (A)
Processing grade: 67
Grade: 67% - Needs Improvement (D)
Processing grade: 105
Error: Grade must be between 0 and 100!

Void functions vs. value-returning functions

Void Functions Value-Returning Functions
Return type: void Return type: int, double, etc.
Don't return a value Return a value
Called as statements Called in expressions
Good for actions/output Good for calculations
#include <iostream>

// Void function - performs action
void displayResult(int result)
{
    std::cout << "The answer is: " << result << std::endl;
}

// Value-returning function - calculates and returns
int multiplyNumbers(int a, int b)
{
    return a * b;
}

int main()
{
    // Call value-returning function and use result
    int result = multiplyNumbers(6, 7);
    
    // Call void function to display result
    displayResult(result);
    
    // Or combine them:
    displayResult(multiplyNumbers(3, 4));
    
    return 0;
}

Output:

The answer is: 42
The answer is: 12

When to use void functions

Use void functions when you want to:

  1. Organize code into logical chunks

    void initializeGame() { /* setup code */ }
    void processUserInput() { /* input handling */ }
    void updateDisplay() { /* screen updates */ }
    
  2. Perform output operations

    void printReport() { /* generate report */ }
    void showErrorMessage() { /* display errors */ }
    
  3. Execute side effects (modify global state, write to files, etc.)

    void savePlayerProgress() { /* save to file */ }
    void playSound() { /* audio output */ }
    
  4. Handle procedures that don't need to return data

    void clearScreen() { /* clear console */ }
    void waitForKeypress() { /* pause program */ }
    

Common mistakes with void functions

❌ Trying to return a value from void function

void badFunction()
{
    return 42;  // Error! Void functions can't return values
}

❌ Trying to use void function result

void printMessage()
{
    std::cout << "Hello!" << std::endl;
}

int main()
{
    int x = printMessage();  // Error! printMessage() doesn't return anything
    return 0;
}

✅ Correct usage

void printMessage()
{
    std::cout << "Hello!" << std::endl;
}

int main()
{
    printMessage();  // Correct - call as statement
    return 0;
}

Best practices for void functions

  1. Use descriptive names that indicate what action the function performs

    void calculateTaxes();     // Good - describes action
    void process();            // Poor - too vague
    
  2. Keep functions focused on one specific task

    // Good - single responsibility
    void validateInput(int value);
    void displayResult(int result);
    
    // Poor - doing too many things
    void validateAndDisplayAndCalculate();
    
  3. Use early returns for error conditions

    void processOrder(int quantity)
    {
        if (quantity <= 0)
        {
            std::cout << "Error: Invalid quantity!" << std::endl;
            return;  // Exit early on error
        }
    
        // Continue with normal processing...
    }
    

Summary

Void functions are essential for organizing code and performing actions that don't need to return values:

  • Use void as the return type for functions that don't return values
  • Void functions can have parameters to customize their behavior
  • Use return; (without a value) to exit early from void functions
  • Void functions are perfect for displaying output, organizing code, and performing actions
  • Call void functions as statements, not in expressions

Void functions help make your code more modular, readable, and maintainable by breaking complex tasks into smaller, focused functions.

Quiz

  1. What does the void keyword mean when used as a function's return type?
  2. Can a void function use a return statement? If so, how?
  3. How do you call a void function in your code?
  4. What's wrong with this code?
    void sayHello() { std::cout << "Hello!\n"; }
    int main() { int x = sayHello(); }
    
  5. When should you use void functions instead of value-returning functions?

Practice exercises

Try creating these void functions:

  1. void printStars(int count) - Print a line of asterisks of specified length
  2. void convertAndDisplay(double celsius) - Convert Celsius to Fahrenheit and display both values
  3. void drawBox(int width, int height) - Draw a rectangle made of '#' characters
  4. void validatePassword(std::string password) - Check if password meets criteria and display appropriate messages

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion