Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better name for CHAR_BIT?

I was just checking an answer and realized that CHAR_BIT isn't defined by headers as I'd expect, not even by #include <bitset>, on newer GCC.

Do I really have to #include <climits> just to get the "functionality" of CHAR_BIT?

like image 560
Potatoswatter Avatar asked Apr 22 '10 06:04

Potatoswatter


People also ask

What is CHAR_BIT?

The CHAR_BIT is the number of bits in char. It is declared in “limits. h” header file in C++ language. It is of 8-bits per byte.

Is CHAR_BIT always 8?

The ISO C Standard requires CHAR_BIT to be at least 8.


2 Answers

As you may know, whether or not an implementation wants to include other headers is unspecified. It's allowed, but not mandated. (§17.4.4.1) So you either have to be explicit or know your guarantees.

The only time a C++ header must include another is if it requires a definition in another. For example, <bitset> is required to include <cstddef> for std::size_t, as this is explicitly stated in the standard. (§23.3.5, for this example)

For a counter-example, consider <limits>. It may include <climits> and define the values for numeric_limits in terms of the macros within, and it often does since that's easiest for an implementation. But all the standard says is things like: "Equivalent to CHAR_MIN, SHRT_MIN, FLT_MIN, DBL_MIN, etc." but doesn't say it must to be implemented in terms of those, which means <climits> doesn't have to be included.

So the only way you can be guaranteed that a CHAR_BIT is defined is by including <climits> or some other header where it's explicitly stated it must include it. And as far as I can tell, none have to; an implementation is free to just hard-code the value everywhere it's needed, for example, or include <limits> and use std::numeric_limits<unsigned char>::digits (which is equivalent).

like image 179
GManNickG Avatar answered Sep 29 '22 18:09

GManNickG


Unless you're programming for DSPs, a better name for it is 8. POSIX and Windows both require CHAR_BIT==8, and that covers pretty much every interesting target conceivable except DSPs. (I would not consider 1970s mainframes a potentially interesting target anymore, but perhaps someone will beg to differ...)

like image 34
R.. GitHub STOP HELPING ICE Avatar answered Sep 29 '22 19:09

R.. GitHub STOP HELPING ICE