amirassov
amirassov

Reputation: 81

Is char the only type with a mandated size?

In the C++ standard:

sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1.

  1. Are there any other types in C++ which have a fixed sizeof?

  2. Does the empty structure correspond to this definition?

Upvotes: 5

Views: 299

Answers (3)

tohava
tohava

Reputation: 5412

Regarding question 1, you also have the types in stdint.h.

Upvotes: -1

Jarod42
Jarod42

Reputation: 218108

1) Are there any other types in C++ which have a fixed sizeof?

There are arrays which have specified size:

sizeof(T[N]) == N * sizeof(T)

so sizeof(char[42]) is 42.

2) Does the empty structure correspond to this definition?

Empty struct is neither char, signed char or unsigned char, so it doesn't correspond to this definition. (BTW its sizeof cannot be 0).

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234835

  1. No. As you say, sizeof(signed char), sizeof(unsigned char), and sizeof(char) are defined by the standard to be 1. Note that char must be either signed or unsigned but it is always considered to be a distinct type. The sizeof anything else is down to the implementation subject to some constraints (e.g. sizeof(long) cannot be less than sizeof(int).)

  2. The C++ standard requires sizeof an empty class to be an integral value greater than zero (otherwise pointer arithmetic would break horribly).

Upvotes: 10

Related Questions