Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is bool guaranteed to be 1 byte?

The Rust documentation is vague on bool's size.
Is it guaranteed to be 1 byte, or is it unspecified like in C++?

fn main() {     use std::mem;     println!("{}",mem::size_of::<bool>()); //always 1? } 
like image 339
Trevor Hickey Avatar asked Jun 27 '16 06:06

Trevor Hickey


People also ask

Is a bool 1 byte?

bool The bool type takes one byte and stores a value of true (1) or false(0). The size of a bool is 1 true 1 1 1 false 0 0 0 Press any key to continue . . . int is the integer data type.

Why does bool require 1 byte?

A bool takes in real 1 bit, as you need only 2 different values. However, when you do a sizeof(bool), it returns 1, meaning 1 byte. For practical reasons, the 7 bits remaining are stuffed. you can't store a variable of size less than 1 byte.

Why is a bool 4 bytes?

Because it's fast. A 32-bit processor typically works with 32-bit values. Working with smaller values involves longer instructions, or extra logic.

How many bytes is a bool in Rust?

It says the size of bool in Rust is 1 byte, and use 0 or 1 to represent both false and true .


1 Answers

Rust emits i1 to LLVM for bool and relies on whatever it produces. LLVM uses i8 (one byte) to represent i1 in memory for all the platforms supported by Rust for now. On the other hand, there's no certainty about the future, since the Rust developers have been refusing to commit to the particular bool representation so far.

So, it's guaranteed by the current implementation but not guaranteed by any specifications.

You can find more details in this RFC discussion and the linked PR and issue.

Edit: Please, see the answer below for more information about changes introduced in Rust since this answer had been published.

like image 102
Andrew Lygin Avatar answered Sep 23 '22 01:09

Andrew Lygin