C C99 `_Bool` Type

beginner
25 min

C C99 _Bool Type

Welcome to our deep dive into the C programming language! Today, we'll explore the _Bool type, a key addition to C99 that enhances the language's ability to handle Boolean values. Let's get started! 🎯

What is a Boolean?

In simple terms, a Boolean is a data type that can have one of two values: true or false. This is commonly used in programming to represent conditions like "is this equal to that?" or "has this happened yet?"

In C, we've traditionally used integers to represent Booleans, with 0 representing false and any non-zero number representing true. However, with the introduction of C99, we now have a dedicated _Bool type to handle Booleans more elegantly. 💡

The _Bool Type

_Bool is a new data type added to C99, specifically designed to handle Boolean values. Here are some key points about this type:

  • It can only hold the values 0 (false) or 1 (true).
  • By default, _Bool values are of size 1 (char-size) on most systems.
  • When used in expressions, _Bool values are promoted to int in C99, making them compatible with traditional Boolean logic.

Using _Bool in C

Let's see how we can use _Bool in C with some practical examples.

Example 1: Simple Boolean Check

c
#include <stdio.h> int main() { _Bool isEven = 4 % 2 == 0; // Assigns 1 (true) if the number is even printf("The number 4 is even: %d\n", isEven); return 0; }

In this example, we declare a variable isEven of type _Bool and assign it the result of a Boolean expression. We then print the result using printf().

Example 2: Using _Bool in Conditional Statements

c
#include <stdio.h> int main() { _Bool isValidAge = 18 <= age && age <= 65; // Use `_Bool` in a conditional statement if (isValidAge) { printf("You are eligible to vote.\n"); } else { printf("You are not eligible to vote.\n"); } return 0; }

In this example, we use a _Bool variable isValidAge in a conditional statement to check if the user's age is within the voting eligibility range. We then display a message based on the condition's result.

Quiz

Quick Quiz
Question 1 of 1

What is the size of `_Bool` in C99?

Remember, using _Bool can make your code cleaner and more readable. Happy coding! ✅

If you found this lesson helpful, consider sharing it with your friends who are learning C programming. Let's help each other grow! 💡