Amiga.org
Operating System Specific Discussions => Amiga OS => Amiga OS -- Development => Topic started by: golem on August 14, 2006, 09:55:26 AM
-
I'm a C novice and have come across an expression I can't get my head round in the RKM examples.
Here is an example;
/* Examine pending messages */
while ( message = (struct IntuiMessage *)GetMsg(win->UserPort) )
(
etc.............
Its the use of the indirection operator I'm unsure of how it works in this context. Is it the same as the below in effect?
(struct IntuiMessage (*GetMsg(win->UserPort))
Help please
:-?
-
@golem
It's typecasting (just 'casting' in short). It's '(type)' before the expression.
GetMsg() returns 'struct Message *', but here we want to assign the return value to 'struct IntuiMessage *' type variable. To avoid a warning about a type mismatch, we need to cast the return value so that it matches the type we assign it to.
Thus:message = [b](struct IntuiMessage *)[/b] GetMsg(...)
Most of the time trying to assign a return value to different type variable is a programming error. When it is not (like for example here), you want to cast the type to tell the compiler you 'really mean it'.
Even more details (ignore this if you don't feel like it yet):
This type of casting is often used when the type returned in embedded inside some other structure. In this case, if you take a look at the struct IntuiMessage from intuition/intuition.h, you will see that:
struct IntuiMessage
{
struct Message ExecMessage;
ULONG Class;
UWORD Code;
...
};
As you can see the structure begins with 'struct Message', and this is what GetMsg() returns pointer to ('struct Message *'). Since we know that intuition sends IDCMP messages of this type to the window UserPort, and GetMsg() will fetch these messages, we can now cast the pointer to 'struct IntuiMessage *' to get access to the other fields.
-
@piru
That's why I like FORTRAN. ;-)
-
Thanks Piru - I think I've asked that before as well but something in my head fights against it. But your explanation is clear. Cheers
-
@weirdami
"That's why I like FORTRAN. "
Not a pro myself, but I've found sometimes casting between diferent types speeds up the code, with other languages you're forced to use 2 variables. Flexibility that comes with a price I guess. I wouldn't wanna use anything without it now though.