Coming Soon

This lesson is currently being developed

Void

Understand the void type and its uses in C++.

Fundamental Data Types
Chapter
Beginner
Difficulty
20min
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.

4.2 — Void

In this lesson, you'll learn about the void data type, which represents "no type" or "no value." Understanding void is crucial for working with functions and pointers in C++.

What is void?

Void is a special data type in C++ that represents "nothing" or "no value." The keyword void comes from the English word meaning "empty" or "containing nothing."

Unlike other data types that represent actual values (like int represents integers), void represents the absence of a value.

Uses of void

1. Void functions (functions that don't return a value)

The most common use of void is for functions that perform an action but don't return a value:

#include <iostream>

// This function prints a message but doesn't return anything
void printWelcome()
{
    std::cout << "Welcome to C++ programming!" << std::endl;
}

// This function takes parameters but doesn't return anything
void printSum(int a, int b)
{
    int sum = a + b;
    std::cout << "The sum of " << a << " and " << b << " is " << sum << std::endl;
}

int main()
{
    printWelcome();        // Call void function
    printSum(5, 3);        // Call void function with parameters
    
    return 0;
}

Output:

Welcome to C++ programming!
The sum of 5 and 3 is 8

2. Functions with no parameters

You can explicitly specify that a function takes no parameters using void:

#include <iostream>
#include <ctime>

// Function that takes no parameters (void can be omitted)
void printCurrentTime()
{
    std::time_t now = std::time(0);
    std::cout << "Current time: " << std::ctime(&now);
}

// Equivalent function (void in parameter list is optional)
void printGreeting(void)  // void here is optional but explicit
{
    std::cout << "Hello, world!" << std::endl;
}

int main()
{
    printCurrentTime();
    printGreeting();
    
    return 0;
}

3. The difference between void and value-returning functions

Here's a clear comparison between void functions and value-returning functions:

#include <iostream>

// Value-returning function - returns a value
int calculateSquare(int number)
{
    return number * number;
}

// Void function - performs action, returns nothing
void printSquare(int number)
{
    int result = number * number;
    std::cout << number << " squared is " << result << std::endl;
}

int main()
{
    // Using value-returning function
    int result = calculateSquare(5);  // Store the returned value
    std::cout << "Result: " << result << std::endl;
    
    // You can use return value in expressions
    int total = calculateSquare(3) + calculateSquare(4);
    std::cout << "3² + 4² = " << total << std::endl;
    
    // Using void function
    printSquare(5);  // Just calls the function, no return value
    
    // This would be an error - void functions don't return values:
    // int error = printSquare(5);  // Error! Can't assign void to int
    
    return 0;
}

Output:

Result: 25
3² + 4² = 25
5 squared is 25

When to use void functions

Void functions are perfect for operations that:

  1. Display output (printing to console, writing to files)
  2. Modify program state (changing global variables, updating objects)
  3. Perform actions (playing sounds, sending network requests)
#include <iostream>

// Global variable to demonstrate state modification
int counter = 0;

// Void function that modifies global state
void incrementCounter()
{
    counter++;
    std::cout << "Counter incremented to: " << counter << std::endl;
}

// Void function that displays information
void showMenu()
{
    std::cout << "\n=== Main Menu ===" << std::endl;
    std::cout << "1. Increment counter" << std::endl;
    std::cout << "2. Show counter" << std::endl;
    std::cout << "3. Exit" << std::endl;
    std::cout << "Choice: ";
}

// Void function that displays current state
void showCounter()
{
    std::cout << "Current counter value: " << counter << std::endl;
}

int main()
{
    showMenu();
    
    // Simulate user interactions
    incrementCounter();  // Action: modify state
    showCounter();       // Action: display information
    incrementCounter();
    showCounter();
    
    return 0;
}

Output:


=== Main Menu ===
1. Increment counter
2. Show counter
3. Exit
Choice: Counter incremented to: 1
Current counter value: 1
Counter incremented to: 2
Current counter value: 2

Common void function patterns

Input/Output operations

#include <iostream>

void getUserInfo()
{
    std::string name;
    int age;
    
    std::cout << "Enter your name: ";
    std::getline(std::cin, name);
    std::cout << "Enter your age: ";
    std::cin >> age;
    
    std::cout << "Hello " << name << ", you are " << age << " years old!" << std::endl;
}

Initialization and setup

#include <iostream>

void initializeProgram()
{
    std::cout << "Initializing program..." << std::endl;
    std::cout << "Loading configuration..." << std::endl;
    std::cout << "Program ready!" << std::endl;
}

void cleanup()
{
    std::cout << "Cleaning up resources..." << std::endl;
    std::cout << "Program terminated." << std::endl;
}

Calculations that print results

#include <iostream>

void calculateAndPrintInterest(double principal, double rate, int years)
{
    double interest = principal * rate * years / 100;
    double total = principal + interest;
    
    std::cout << "Principal: $" << principal << std::endl;
    std::cout << "Interest Rate: " << rate << "%" << std::endl;
    std::cout << "Years: " << years << std::endl;
    std::cout << "Interest Earned: $" << interest << std::endl;
    std::cout << "Total Amount: $" << total << std::endl;
}

int main()
{
    calculateAndPrintInterest(1000.0, 5.0, 3);
    return 0;
}

Output:

Principal: $1000
Interest Rate: 5%
Years: 3
Interest Earned: $150
Total Amount: $1150

You cannot create void variables

Unlike other data types, you cannot declare variables of type void:

// These are ERRORS - you cannot create void variables
// void x;           // Error! Cannot declare void variable
// void value = 5;   // Error! Cannot assign to void variable

// These are correct uses of void:
void printMessage();  // Function declaration with void return type
void doSomething(void);  // Function with no parameters (explicit)

Void pointers (advanced topic preview)

While you can't have void variables, C++ does have void pointers (void*) which can point to any data type. This is an advanced topic you'll encounter later:

#include <iostream>

int main()
{
    int number = 42;
    double decimal = 3.14;
    
    // Void pointer can point to any type (advanced topic)
    void* ptr;
    ptr = &number;    // Points to int
    ptr = &decimal;   // Points to double
    
    std::cout << "Void pointers are used in advanced programming" << std::endl;
    
    return 0;
}

Best practices with void functions

✅ Use descriptive names for void functions

// Good: Clear what the function does
void displayWelcomeMessage();
void calculateAndPrintTaxes();
void initializeGameState();

// Less clear: What does it do?
void process();
void handle();
void doStuff();

✅ Keep void functions focused on one task

// Good: Single responsibility
void printHeader()
{
    std::cout << "=== My Program ===" << std::endl;
}

void printFooter()
{
    std::cout << "Thank you for using our program!" << std::endl;
}

// Less ideal: Multiple responsibilities
void printHeaderAndFooterAndMenu()
{
    std::cout << "=== My Program ===" << std::endl;
    std::cout << "1. Option 1" << std::endl;
    std::cout << "2. Option 2" << std::endl;
    std::cout << "Thank you for using our program!" << std::endl;
}

✅ Use void functions for side effects

#include <iostream>

// Good use of void: Function has a side effect (printing)
void logMessage(const std::string& message)
{
    std::cout << "[LOG] " << message << std::endl;
}

int main()
{
    logMessage("Program started");
    logMessage("Processing data");
    logMessage("Program completed");
    
    return 0;
}

Summary

The void type represents "no value" or "nothing" in C++:

  • Void functions don't return values - they perform actions
  • Use void functions for operations like printing, modifying state, or performing tasks
  • You cannot create variables of type void
  • Void functions are essential for organizing code into logical, reusable pieces
  • Function parameters can explicitly use void to indicate no parameters (though this is optional in C++)

Void functions are the "doers" of your program - they make things happen without necessarily producing a value to be used elsewhere.

Quiz

  1. What does the void data type represent in C++?
  2. Can you create a variable of type void? Why or why not?
  3. What's the difference between a void function and a value-returning function?
  4. When should you use a void function instead of a value-returning function?
  5. What happens if you try to assign the result of a void function to a variable?

Practice exercises

Try creating these void functions:

  1. void printRectangle(int width, int height) - Prints a rectangle of asterisks with given dimensions
  2. void convertAndPrintTemperature(double celsius) - Converts Celsius to Fahrenheit and prints both values
  3. void printMultiplicationTable(int number) - Prints the multiplication table for a given number
  4. void greetUser(const std::string& name, int age) - Prints a personalized greeting message

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