Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is char guaranteed to be exactly 8-bit long? [duplicate]

Tags:

c

types

char

That's all. Didn't find any similar topic so bear with me it there is.

like image 535
Ori Popowski Avatar asked May 19 '09 10:05

Ori Popowski


People also ask

Is a char always 8 bits in C?

that a char is represented by a byte, that a byte can always be counted upon to have 8 bits, that sizeof (char) is always 1 , and that the maximum theoretical amount of memory I can allocate (counted in char s) is the number of bytes of RAM (+ swap space).

Is a char 8-bit?

The char type takes 1 byte of memory (8 bits) and allows expressing in the binary notation 2^8=256 values. The char type can contain both positive and negative values. The range of values is from -128 to 127.

Is sizeof char guaranteed to be 1?

Even if you think of a “character” as a multi-byte thingy, char is not. sizeof(char) is always exactly 1. No exceptions, ever.

How many bits is a char in C?

The smallest group of bits the language allows use to work with is the unsigned char , which is a group of 8 bits.


1 Answers

From a copy of the ANSI C specification, see Section 3.1.2.5 - Types:

An object declared as type char is large enough to store any member of the basic execution character set. If a member of the required source character set enumerated in $2.2.1 is stored in a char object, its value is guaranteed to be positive. If other quantities are stored in a char object, the behavior is implementation-defined: the values are treated as either signed or nonnegative integers.

The concept of "execution character set" is introduced in Section 2.2.1 - Character sets.

In other words, a char has to be at least big enough to contain an encoding of at least the 95 different characters which make up the basic execution character set.

Now add to that the section 2.2.4.2 - Numerical limits

A conforming implementation shall document all the limits specified in this section, which shall be specified in the headers <limits.h> and <float.h> .

Sizes of integral types

The values given below shall be replaced by constant expressions suitable for use in #if preprocessing directives. Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.

  • maximum number of bits for smallest object that is not a bit-field (byte)
    CHAR_BIT 8

  • minimum value for an object of type signed char
    SCHAR_MIN -127

  • maximum value for an object of type signed char
    SCHAR_MAX +127

  • maximum value for an object of type unsigned char
    UCHAR_MAX 255

....

So there you have it - the number of bits in a char must be at least 8.

like image 193
Paul Dixon Avatar answered Sep 23 '22 08:09

Paul Dixon