Flip That Bit

All the nonsense that takes place in programming happens because it’s possible to change the value of a bit from 0 to 1 and back again. The general concept is known as a toggle switch: The item can be set and reset between on and off positions.

Most C language programmers use an int variable as a toggle switch. The variable is set to 1 or 0 for TRUE/FALSE or On/Off — however you want to look at it.

You can also use the _Bool variable type, providing that your compiler is C99 compatible, which in 2015 it should be.

_Bool comes from Boolean (boo’-lee-an), which is named after British mathematician George Boole. I find it enjoyable to say the word, “Boolean.”

Using the _Bool variable type isn’t as popular as using an int, probably because most C programmers are of the grizzled, bearded, sandal-wearing, Unix variety and they grumble and grouse about the underscore keywords introduced with the C99 standard.

Whatever.

Here is sample code that makes used of the _Bool variable type:

#include <stdio.h>

int main()
{
    _Bool bit;

    bit = 0;
    printf("The value of _Bool 'bit' is %d\n",bit);
    printf("The size of _Bool 'bit' is %lu\n",sizeof(bit));

    return(0);
}

Here’s the output:

The value of _Bool 'bit' is 0
The size of _Bool 'bit' is 1

For this month’s exercise, you must work with an array of 10 Boolean values:

_Bool toggle[10] = {
    1, 0, 1, 1, 0, 1, 1, 0, 1, 0
};

Your code must take each Boolean value in the array and flip it, changing 1 to 0 and 0 to 1. This is a pretty basic programming operation, and I can imagine several ways to accomplish this task.

Don’t let the _Bool variable type confuse you. The array could very well just be int values and the result would be the same.

Click here to view my solution. As usual, please try this Exercise on your own before you peek at what I’ve done.

Leave a Reply