bool and void Data Types in C++

In C++, bool and void are important data types used for logical operations and function definitions.

Understanding these types helps in writing efficient conditional logic and function structures.

1. Boolean Data Type (bool)

The bool data type represents logical values: true or false.

It is commonly used in conditions, loops, and decision-making statements.

C++
Boolean example
#include <iostream>
using namespace std;

int main() {
    bool isActive = true;
    cout << isActive;
    return 0;
}

2. Boolean Values

true → 1

false → 0

3. Usage of bool

1. Conditional statements (if, else).

2. Loop control.

3. Logical operations.

4. Void Data Type

The void data type represents the absence of value.

It is mainly used in functions that do not return any value.

5. Void Function Example

C++
Void function
#include <iostream>
using namespace std;

void greet() {
    cout << "Hello";
}

int main() {
    greet();
    return 0;
}

6. Void Pointer

A void pointer is a generic pointer that can hold the address of any data type.

C++
Void pointer example
int x = 10;
void* ptr = &x;

7. Difference Between bool and void

bool: Stores true or false values.

void: Represents no value.

8. Real-World Usage

bool is used in login validation, conditions, and flags. void is used in functions that perform actions without returning data.

9. Common Mistakes

1. Using void as a variable type.

2. Forgetting return in non-void functions.

3. Misusing boolean values.

10. Best Practices

1. Use bool for conditions.

2. Use void for functions without return.

3. Write clear logical expressions.

4. Avoid unnecessary conversions.

11. Practice Exercises

1. Create a boolean condition program.

2. Write a void function.

3. Use a void pointer.

Conclusion

The bool and void data types play important roles in C++ programming.

Understanding their usage helps in building logical and structured programs.