Anonymous Uniouns

R

Raj

Hi friends....

Could any one tell me atleast one application of anonymous uniouns in
C++?

Thank you
 
J

James Aguilar

Homework questions that people on a newsgroup would rather not answer
for you?
 
Z

Zara

Hi friends....

Could any one tell me atleast one application of anonymous uniouns in
C++?

Thank you

Transmogrifying normal unions into state-of-the-art maintainer traps
 
T

Tom

Hi friends....

Could any one tell me atleast one application of anonymous uniouns in
C++?

Thank you

Very interesting. I've never even heard of them before.

http://windowssdk.msdn.microsoft.co...html/36da2365-06a0-4e22-9665-e89eb28358ad.asp

So ... I played around with them a bit and modified the above example
program (see below). Note how the printed out value of x changes.
Demonstrating that the union's variables are sharing the same memory
space. My C++ I/O skills are still lacking -- so I used my good ol'
friend printf().

What good is it? It allows a list of variables of varying type to
share the memory space of the longest type. Thus conserving memory
resources. Now, let's make everyone cringe. Just buy a gig of ram and
declare a bunch of global variables and don't worry about conserving
memory. :))

// anonymous_unions.cpp
// compile with: /EHsc
#include <iostream>
#include <stdio.h>

using namespace std;
int main() {
union {
int d;
char *f;
double x;
};

f = "test";
x = 999999999999.999;
printf("x = %18.3f\n", x);
d = INT_MAX;
cout << "INT_MAX = " << d << endl;
printf("x = %18.3f\n", x);
f = "here's a really long string stored in stack memory and not
allocated until run time; however, the pointer address resides in the
anonymous union";
cout << f << endl;
cout << " sizeof(int): " << sizeof(int) << endl;
cout << "sizeof(double): " << sizeof(double) << endl;
cout << " sizeof(char*): " << sizeof(char*) << endl;
}
// Program Output
// x = 999999999999.999
// INT_MAX = 2147483647
// x = 999999930368.000
// here's a really long string stored in stack memory and not
allocated until run time; however, the pointer address resides in the
anonymous union
// sizeof(int): 4
// sizeof(double): 8
// sizeof(char*): 4
 
B

benben

Raj said:
Hi friends....

Could any one tell me atleast one application of anonymous uniouns in
C++?

Thank you

Constructing (almost) variant data type (almost) without dynamic memory
allocation.

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top