Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Boolean variables in C

Name: Anonymous 2010-05-30 12:44

Has anyone created a method for using a byte as 8 boolean variables in C? I could implement it myself, but I'm curious, as it seems that the usual is to use a whole int for logical values. What I mean is something like this:

bool a;
bool b;
bool c;
bool d;
bool e;
bool f;
bool g;
bool h;
bool i;


And from a to h it would use just one byte, but when it's going to allocate memory for i it would the first bit from another byte. Also, is this how C++ implements its boolean types, or does it use a integer per boolean variable?

Name: sage 2010-05-30 13:14

>>1
Has anyone created a method for using a byte as 8 boolean variables in C?

First of all, 10/10 IHBT, A+ would be trolled again etc.

Secondly... People have been doing this for the entire history of computer programming.  I hope that you are a relatively new programmer, otherwise I will have to slap you for not knowing that everyone already started doing this decades ago.

#include <stdio.h>
#include <stdint.h>

#define BITSET(v, bit)          (v |= (1 << bit))
#define BITCLEAR(v, bit)        (v &= ~(1 << bit))
#define ISBIT(v, bit)           (v & (1 << bit))
#define BITTOGGLE(v, bit)       (v ^= (1 << bit))

int main(void) {
    uint8_t n = 0;
    if (ISBIT(n, 0)) { // false
        printf("Bit 0 is set in the value %i.\n", n);
    }
    BITSET(n, 0);
    if (ISBIT(n, 0)) { // true
        printf("Bit 0 is set in the value %i.\n", n);
    }
    n = 255;
    BITTOGGLE(n, 7);
    printf("255, but with bit7 toggled off == %i\n", n);
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List