Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sizeof(T) == sizeof(const T) and alignof(T) == alignof(const T)

It seems reasonable to assume that T and const T would be two types that would be the same size and have the same alignment, but after thinking about some real systems, it seems that they could be different.

Let me explain:

Suppose you have a system with two types of memory: RAM and Flash (which is read only). The RAM is 8 bit addressable, while the Flash is only 16 bit addressable. Suppose this is T:

struct T {   uint8_t x;   uint16_t y; }; 

In the byte addressable RAM this struct would be 3 bytes long.... but in the double byte addressable Flash (which is where a const variable would reside) this struct would have to be at least 4 bytes long, because of alignment issues.

So here is my question:

Do the c and c++ standards guarantee the sizes and alignment of const and nonconst types?

like image 471
DarthRubik Avatar asked Aug 06 '16 02:08

DarthRubik


2 Answers

Section 3.9.3:

The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements (3.11). 53

"cv-qualified" here refers to const and volatile. So the answer is, yes.

const and volatile only specify the limitations/attributes of access to the specified object. They are not considered to be a part of the base type itself; hence they cannot affect the type's properties.

like image 188
Sam Varshavchik Avatar answered Sep 30 '22 18:09

Sam Varshavchik


Yes, this is guaranteed by [basic.type.qualifier] / 1

The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements (3.11).

like image 27
user657267 Avatar answered Sep 30 '22 17:09

user657267