nightlytrails
nightlytrails

Reputation: 2662

uint8_t - 8 bits guarantee

How & where is it guaranteed that an uint8_t is 8-bits?

Digging into N3242 - "Working Draft, Standard for Programming Language C++", section 18.4.1 < cstdint > synopsis says -

       `typedef unsigned integer type uint8_t; // optional`

So, in essence, a C++ standard conforming library is not needed to define uint8_t at all.

Update: Probably am just asking, which line of the standard says that uintN_t types are N bits?

Upvotes: 1

Views: 2113

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

The <stdint.h> types are defined with reference to the C99 standard.

C99 draft N869 §7.17.1.1/2:
“The typedef name uintN_t designates an unsigned integer type with width N. Thus, uint24_t denotes an unsigned integer type with a width of exactly 24 bits.”

If a type is defined by <stdint.h>, then so are its associated macros, and if the type is not defined, then neither are its associated macros, by C99 §7.18/4.

Thus, you can use the existence or not of the macro UINT8_MAX (required by C99 §7.18.2.1) to check for the presence or absence of the uint8_t type definition.

Upvotes: 3

justin
justin

Reputation: 104698

From C++:

18.4.1 Header synopsis

... The header defines all functions, types, and macros the same as 7.18 in the C standard. ...

From C:

7.20.1.1 Exact-width integer types

1 The typedef name intN_t designates a signed integer type with width N , no padding bits, and a two’s complement representation. Thus, int8_t denotes such a signed integer type with a width of exactly 8 bits.

2 The typedef name uintN_t designates an unsigned integer type with width N and no padding bits. Thus, uint24_t denotes such an unsigned integer type with a width of exactly 24 bits.

3 These types are optional. However, if an implementation provides integer types with widths of 8, 16, 32, or 64 bits, no padding bits, and (for the signed types) that have a two’s complement representation, it shall define the corresponding typedef names.


So, in essence, a C++ standard conforming library is not needed to define uint8_t at all.

Correct. As Nikos mentioned (+1), you just need an alternative when/if the typedef is not present/declared.

Upvotes: 6

Nikos C.
Nikos C.

Reputation: 51850

uint8_t is guaranteed to be 8 bits wide. If it doesn't exist, then obviously you can't use it. But if it's there, it's 8 bits. There's no possibility where it's provided but is not 8 bits.

Upvotes: 1

Related Questions