cgccicc

storage of bool in c under various compilers and optimization levels


trivial example program:

#include <stdio.h>
main()
{
    bool tim = true;
    bool rob = false;
    bool mike = true;

    printf("%d, %d, %d\n", tim, rob, mike);

}

Using the gcc compiler it appearers, based on looking at the assembly output, that each bool is stored as a bit in individual bytes:

0x4004fc <main()+8>          movb      $0x1,-0x3(%rbp)
0x400500 <main()+12>         movb      $0x0,-0x2(%rbp)
0x400504 <main()+16>         movb      $0x1,-0x1(%rbp)

if, however, one turns optimization on, is there a level of optimization that will cause gcc to store these bools as bits in a byte or would one have to put the bools in a union of some bools and a short int? Other compilers? I have tried '-Os' but I must admit I can't make heads or tails of the output disassembly.


Solution

  • @Keith Thompson's good answer can explain what happened with the code example in the question. But I'll assume that the compiler doesn't transform the program. According to the standard, a bool (a macro in stdbool.h the same as the keyword _Bool) must have a size of one byte.

    C99 6.2.6.1 General

    Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number, order, and encoding of which are either explicitly specified or implementation-defined.

    This means that any type(except bit-fields, including bool) of objects must have at least one byte.

    C99 6.3.1.1 Boolean, characters, and integers

    The rank of_Bool shall be less than the rank of all other standard integer types.

    This means bool's size is no more than a char(which is an integer type). And we also know that the size of an char is guaranteed to be one byte. So the size of bool should be at most one byte.

    Conclusion: the size of bool must be one byte.