On 12/26/2011 10:50 AM, Nephi Immortal wrote:
> On Dec 25, 7:54 am, Victor Bazarov<v.baza...@comcast.invalid> wrote:
>> On 12/25/2011 7:20 AM, Kalle Olavi Niemitalo wrote:
>>
>>
>>
>>
>>
>>> Nephi Immortal<immortalne...@gmail.com> writes:
>>
>>>> enum has four constants and require additional 16 bytes.
>>
>>> Usually not true. In typical implementations of C++ (and C),
>>> if you compile
>>
>>> enum { zero, one, two, three };
>>> int f(const int p[])
>>> {
>>> return p[two] - p[three];
>>> }
>>
>>> the generated code and data are the same as if you had compiled
>>
>>> int f(const int p[])
>>> {
>>> return p[2] - p[3];
>>> }
>>
>>> i.e. the enum type does not take up space in the executable
>>> program. It does take up space in debug information, symbol
>>> tables, and such; but if you are compiling for a device with so
>>> little memory that you need to worry about 16 bytes, then you
>>> probably will not install those things into the device anyway.
>>
>>>> Do you have idea if there is another way how to overcome union to
>>>> accept const instead of static const?
>>
>>> If the union does not need to be anonymous, you can do this:
>>
>>> static const union
>>> {
>>> char str[ 5 ];
>>> struct Letter
>>> {
>>> char a;
>>> char b;
>>> char c;
>>> char d;
>>> } letter;
>>> } u = {"ABCD"};
>>
>>> int main()
>>> {
>>> char A = u.letter.a; // read 'A' from str and put it in A variable
>>> char B = u.letter.b; // read 'B' from str and put it in B variable
>>> char C = u.letter.c; // read 'C' from str and put it in C variable
>>> char D = u.letter.d; // read 'D' from str and put it in D variable
>>> }
>>
>> Strictly speaking, the point of unions is to share the memory, the
>> ability to store something, BUT NOT the value of it. The 2003 Standard
>> still allowed to read only the value that was put in the union, but
>> never write one part and read another. That actually has undefined
>> behavior. I don't know whether that was relaxed in C++11.
>
> However, all five variables share the same memory address as long as
> you can do read only AND read/write only.[..]
If you write one member of the union, any attempt to read another member
of the union has undefined behavior, unless they are both POD and share
the same layout. See Michael's post explaining that you *might* still
be OK if we somehow consider that four 'char' members of your 'struct
Letter' have the _same layout_ as the five-element array or char.
Whatever tricks you want to play with addresses is system-, compiler-
and platform-specific, and any use of it is at the risk of the one who
uses it, the *Standard* does not specify any behavior for it. That's all.
V
--
I do not respond to top-posted replies, please don't ask
|