All abt enum range

An enumerator can be initialized by a
>     constant-expression of integral type.  The
>     range of an enumeration holds all the
>     enumeration’s enumerator values rounded up to
>     the nearest larger binary power minus 1.
>
>     “The range goes down to 0 if the smallest
>     enumerator is non-negative and to the nearest
>     lesser negative binary power if the smallest
>     enumerator is negative.  This defines the
>     smallest bit-field capable of holding the
>     enumerator values.”
>

Pay special attention to the phrase: “enumerator values
rounded up to the nearest larger binary power minus 1”, and:
“The range goes down to 0 if the smallest enumerator is
non-negative”.

> For example,
>
> enum e1      {dark, light};               // range 0:1
> enum e2      {a = 3, b = 9};              // range 0:15
> enum e3      {min = -10, max = 1000000};  // range -1048576:1048575
> enum flag    {x = 1, y, z = 4, e = 8};    // range 0:15
>

Take enum e2 for example.  Number of bits required to
represent 3 is two (i.e., 11 binary is 3 decimal).
Similarly, number of bits required to represent 9 is four
(i.e., 1001 binary is 9).  Nearest larger binary power minus
one: (2^4)-1 = 15.  Hence the upper limit is 15.

To find the lowest limit of the range, it says if the
smallest enumerator (3 in this case) is non-negative, then
the range goes down to zero.  Hence the range of enumerator
e2 is 0 to 15.

enum flag is similar to enum e2.

In the enum e1, only one bit is required to represent dark
and light values, 0 and 1 respectively.  Hence the range is
also 0 to 1.

For enum e3, max requires 20 bits for binary representation.
Pay attention to this phrase: “… and to the nearest lesser
negative binary power if the smallest enumerator is
negative”.  The smallest enumerator, min, is negative.  So
the lowest value in the range is: -(2^20-1) = -1048576; and
highest value in the range is (2^20)-1 = 1048575.

Advertisements

4 Responses to “All abt enum range”

  1. Mr WordPress Says:

    Hi, this is a comment.
    To delete a comment, just log in, and view the posts’ comments, there you will have the option to edit or delete them.

  2. C++ Says:

    valuable. thanks.

  3. C++ Says:

    valuable, thanks.

  4. amneet Says:

    thanks for clearing the phrases of Bjarne Stroustrup … I was always confused about these phrases.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: