0

In the following example, can I define the size of a C element in bits?

#include <stdio.h>

typedef enum {
    false = 0,
    true = ~0
} bool;

int main(void) {
    bool x;
    printf("%d", sizeof x);
    return 0;
}
motoku
  • 1,571
  • 1
  • 21
  • 49

2 Answers2

6

In general, no. The minimum addressable unit is a byte, not a bit.

You can do funny things with bitfields, such as:

struct {
    unsigned a : 31;
    unsigned b : 1;
};

That struct will likely have a sizeof == 4, a will use 31 bits of space, and b will use 1 bit of space.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • +1. I notice (and appreciate) you use _likely_. It does depend on things like ***[THIS](http://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/)***. – ryyker Mar 24 '14 at 22:05
  • From what I recall with working on embedded systems (it's been a while), compilers render single bit bitfields as efficiently as you'd imagine, but multi-bit fields are a crap-shoot in terms of efficiency. Safer to just use masks. – Nick T Mar 24 '14 at 22:09
0

enum is of int size. All i need to do is make the implicit cast explicit.

#include <stdio.h>

typedef enum {
    true = ~(int)0,
    false = (int)0
} bool;

int main(void) {
    return false;
}
motoku
  • 1,571
  • 1
  • 21
  • 49