Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is char the only type with a mandated size?

Tags:

c++

sizeof

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?

like image 769
amirassov Avatar asked Jan 17 '17 09:01

amirassov


2 Answers

  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).

like image 136
Bathsheba Avatar answered Sep 16 '22 22:09

Bathsheba


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).

like image 20
Jarod42 Avatar answered Sep 20 '22 22:09

Jarod42