473,659 Members | 2,872 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting a structure to an int

I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )

union
{
char ch[4];
int i[2];
} my_union;

long longvar;

longvar = (long)my_union; Illegal cast
//////////////// ILLEGAL
longvar = CAST(long, my_union); Legal cast

I understands that why the CAST macro works but I cannot understands
that what is the problem in the following casting :

longvar = (long)my_union;

Can somebody please tell me that what is the problem in the above
casting mechanism?

PS This is not an assignment. I took this code from the following
link:
http://paul.rutgers.edu/~rhoads/Code/cast_anything.c

Feb 13 '06 #1
12 1947
Hello,

See inserted comments:

ca********@yaho o.com wrote:
I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )

union
{
char ch[4];
int i[2];
} my_union;

long longvar;

longvar = (long)my_union; Illegal cast
//////////////// ILLEGAL
Sizeof of my_union? and sizeof of long?
longvar = CAST(long, my_union); Legal cast

I understands that why the CAST macro works but I cannot understands
that what is the problem in the following casting :

longvar = (long)my_union;

Can somebody please tell me that what is the problem in the above
casting mechanism?

PS This is not an assignment. I took this code from the following
link:
http://paul.rutgers.edu/~rhoads/Code/cast_anything.c


"cast anything or the first bytes of anything or even all it and some
parts of who knows what". Practical, nice and dangerous.

Kind regards.

Feb 13 '06 #2
ca********@yaho o.com wrote:
I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )


A perfect example of what shouldn't be done.
Feb 13 '06 #3
ca********@yaho o.com writes:
I understands that why the CAST macro works but I cannot understands
that what is the problem in the following casting :

longvar = (long)my_union;


In a cast expression, the expression whose value is cast must
have a scalar type, but a union is not a scalar type. (A scalar
type is an arithmetic type or a pointer type.)
--
"I should killfile you where you stand, worthless human." --Kaz
Feb 13 '06 #4


ca********@yaho o.com wrote On 02/13/06 14:08,:
I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )


"Anything?"

CAST(void, stdin)

CAST(char*, printf)

CAST(double, 42)

... and I imagine other examples could be dreamed up.

But even for those cases where there's no compile-time
error, the whole idea is wrong-headed. All CAST attempts
to do is re-interpret the bits of one thing as if they had
some other type. There's no attempt to convert, no concern
for safety, and no reason to rely on whatever result you
might happen to get. It's a Bad Idea, almost always --
and you can delete the "almost" if you're trying to write
code that's even marginally portable.

--
Er*********@sun .com

Feb 13 '06 #5
ca********@yaho o.com wrote:
I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )

union
{
char ch[4];
int i[2];
} my_union;

long longvar;

longvar = (long)my_union; Illegal cast
//////////////// ILLEGAL
longvar = CAST(long, my_union); Legal cast

I understands that why the CAST macro works but I cannot understands
that what is the problem in the following casting :

longvar = (long)my_union;

Can somebody please tell me that what is the problem in the above
casting mechanism?

PS This is not an assignment. I took this code from the following
link:
http://paul.rutgers.edu/~rhoads/Code/cast_anything.c


First of all: This is not a safe technique.

long longvar = (long)my_union;
is just an explicit version of
long longvar = my_union;
because a cast is just an explicit conversion.

As there is no way to convert an arbitrary aggregate type
into an integer type, your compiler will complain.

So, what is the "trick" with the CAST macro?
You do not take the "value" of the aggregate but the
_representation _.
CAST(long, my_union);
tells the compiler to take the bit pattern at &my_union
and pretend that it is the bit pattern of a long.

When does this work guaranteedly?
Whenever the first argument of the CAST macro is
1) of type unsigned char or
2) if the second argument is of structure type, of
the type of the first member
3) if the second argument is of union type, of the
type of the member which has been last written to
4) if the second argument is of array type, of the
type of the array elements
5) a "recursive mixture" of 2)-4)

Example for 5)

struct { union { short foo[5]; float bar[3] } baz } qux;
short firstfoo;

qux.baz.foo[0] = 7;
firstfoo = CAST(short, qux);

There are other times when this works but this is a
implementation dependent thing.

When will it break?
Imagine your example for
sizeof (long) == 8
sizeof (int) == 2 or sizeof (int) == 4
and alignment requirement "long address can be divided
by 8 without remainder, int address can be divided by
2 (or 4, respectively) without remainder".
Then the above can go wrong
a) if the union has an address accommodating the alignment
requirement of int but not of long
b) sizeof (int) == 2: sizeof (long) > sizeof my_union, i.e.
the "CAST" accesses storage which does not belong to
my_union. This gives you either an arbitrary value for
longvar or an access to storage which does not belong
to your program
c) long has a trap representation which has been generated
using my_union.ch
d) a combination of a)-c)
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Feb 13 '06 #6

<ca********@yah oo.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )
oh dear. Bracket in the wrong place -- needs to be

#define CAST(new_type,o ld_object) (*(new_type *)&(old_object) )
or it won't always work.

(It won't work with array types either, but you can get round that with a
typedef)


union
{
char ch[4];
int i[2];
} my_union;

long longvar;

longvar = (long)my_union; Illegal cast
//////////////// ILLEGAL
longvar = CAST(long, my_union); Legal cast

I understands that why the CAST macro works but I cannot understands
that what is the problem in the following casting :

longvar = (long)my_union;


You can't convert a variable. You can only fetch its value and convert
that. But you can only do that with a scalar. Converting the "value" of an
array or struct or union doesn't make any sense

--
RSH

Feb 13 '06 #7
Robin Haigh wrote:
<ca********@yah oo.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )


oh dear. Bracket in the wrong place -- needs to be

#define CAST(new_type,o ld_object) (*(new_type *)&(old_object) )
or it won't always work.

(It won't work with array types either, but you can get round that with a
typedef)


What do you mean?

#include <stdio.h>

#define UNSAFE_CAST(new _type, old_object) \
(*((new_type *)&(old_object) ))

int main (void)
{
short foo[5] = {42, 1, 2, 3, 4};

printf("&foo[0]: %p, &foo: %p\n",
(void *)&foo[0], (void *)&foo);
printf("foo[0]: %d\n", UNSAFE_CAST(sho rt,foo));

return 0;
}

<snip!>

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Feb 13 '06 #8
ca********@yaho o.com wrote:

I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )

union
{
char ch[4];
int i[2];
} my_union;

long longvar;

longvar = (long)my_union; Illegal cast
//////////////// ILLEGAL
longvar = CAST(long, my_union); Legal cast

I understands that why the CAST macro works but I cannot understands
that what is the problem in the following casting :

longvar = (long)my_union;

Can somebody please tell me that what is the problem in the above
casting mechanism?

[...]

You cannot simply cast from a union to a long, which is what you are
trying to do with the direct cast.

However, the CAST() macro does not directly cast from a union to a
long. Rather, it takes the address of the union, casts that to a
"long *", and then dereferences the pointer.

CAST(long,my_un ion)

expands to

*(long *)&my_union

Note, of course, that the above is not a very "safe" thing to be doing.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Feb 13 '06 #9

"Michael Mair" <Mi**********@i nvalid.invalid> wrote in message
news:45******** ****@individual .net...
Robin Haigh wrote:
<ca********@yah oo.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
I recently came across the following CAST macro which can cast anything
to any other thing:

#define CAST(new_type,o ld_object) (*((new_type *)&old_object) )


oh dear. Bracket in the wrong place -- needs to be

#define CAST(new_type,o ld_object) (*(new_type *)&(old_object) )
or it won't always work.

(It won't work with array types either, but you can get round that with a
typedef)


What do you mean?


I only meant, if new_type is int[3], you'll get (int[3]*), which will be a
syntax error. You can't always generate the name of a pointer type just by
adding a * on the end of something.

--
RSH
Feb 13 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
2100
by: j0mbolar | last post by:
I was reading page 720 of unix network programming, volume one, second edition. In this udp_write function he does the following: void udp_write(char *buf, <everything else omitted) struct udpiphdr *ui; struct ip *ip; ip = (struct ip *) buf;
1
1878
by: rahul8143 | last post by:
hello, In kernel source code there is ip_fragment.c file my question is regarding pointer function and casting for that look at required snippet from that file There is structure defined for queueing ip fragments as struct ipq { struct ipq *next; /* linked list pointers */ struct list_head lru_list; /* lru list member */ u32 user; u32 saddr;
61
4548
by: Ken Allen | last post by:
I am relatively new to .Net, but have been using VB and C/C++ for years. One of the drawbacks with VB6 and earlier was the difficulty in casting a 'record' to a different 'shape' so one could perform different manipulations on it. For example, I have a complex data structure, which I can represent in a VB6 TYPE declaration, but I cannot easily convert that to a fixed length array of unsigned bytes so that I could perform a checksum...
2
2162
by: Enrique Bustamante | last post by:
Casting arrays that works on watch and command window but not in code. My application is casting arrays in a way it should work. To test if I was doing something invalid, I wrote a test code that has similar structure of the classes in my application. The test worked fine, the casting I want to do must work. I compared the structure of the test with the application to ensure they where similar (inheriting twice, base class implements...
8
5651
by: wkaras | last post by:
In my compiler, the following code generates an error: union U { int i; double d; }; U u; int *ip = &u.i; U *up = static_cast<U *>(ip); // error I have to change the cast to reinterpret_cast for the code
9
430
by: Roman Mashak | last post by:
Hello, All! I met this code recently on some open source sites. What may be the point of using such construction: typedef struct cmd { unsigned int cmdack; unsigned int code; unsigned int data;
3
2756
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some dead ends. I'm posting this to get some feedback on wether I'm going in the right direction, and at the same time hopefully save others from going through the process.
4
15237
by: Schkhan | last post by:
Hi, I am sturggling with a peace of code mainly its about casting a pointer to one type of structure to a pointer to another type of structure. the confusion begins with the following line...(modified to highlight the actual prob) #define TEST_MACRO(first) ((struct second *) &first) /*here it would return a pointer to second, but the question is why it uses Here in this example "first" and "second" are two different structures*/
101
4293
by: Tinkertim | last post by:
Hi, I have often wondered if casting the return value of malloc() (or friends) actually helps anything, recent threads here suggest that it does not .. so I hope to find out. For instance : char *tmp = NULL;
0
8332
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8525
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2750
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.