Why boolean is 4 bytes instead of 1 byte in struct

Hi all,

I’m having trouble understanding why boolean is taking 4 bytes instead of 1 byte in structs.
Here is an example:

struct F8
    p::Float32
    t::Float32
end
get_F8() = F8(0.0f0, 0.0f0)
println(sizeof(get_F8())) # 8 bytes, correct

struct F12
    p::Float32
    t::Float32
    b::Bool # why 4 bytes?
end

get_F12() = F12(0.0f0, 0.0f0, true)
println(sizeof(get_F12())) # 12 bytes, incorrect was expecting 9 bytes

struct F1
    b::Bool # 1 byte
end
get_F1() = F1(true)
println(sizeof(get_F1())) # 1 byte, correct

Thanks! :smiley:

The Bool is 1 byte, but there are 3 bytes of padding. Julia (and most other languages) pad structs to prevent memory alignment issues.

7 Likes

I did not know that, thanks!

1 Like

Note that it’s worth keeping padding in mind when ordering your fields:

julia> sizeof((1,true,1,true))
32

julia> sizeof((1,1,true,true))
24

We can avoid excessive padding by grouping the Bools together.

13 Likes