Re: [Newbie] When to use *_IS_* macro?



On Wed, Dec 12, 2012 at 02:09:09PM +0100, Guilhem Bonnefille wrote:
> My understanding is these macro allow safe "down-casting".

They are meant both for up-casting and down-casting and also casting to
interfaces (whatever you call that).  They do two things:

1) type-cast pointer to one C struct to pointer to another C struct
2) (if not disabled with G_DISABLE_CAST_CHECKS) check that this typecast
   is valid in the GLib type system

> In the other hand, GTK_IS_DIAL seems not necessary
> in gtk_dial_get_adjustment as C compiler will ensure (gruik cast excepted)
> that argument is in the right type.

The C compiler will not ensure anything because it cannot.

In C, all the different GLib types are just pointers and can be typecast
freely to each other (possibly with a warning if the types do not match
exactly).  The C compiler does not know that GLib implemented some class
hierarchy using plain C structures; it has no notion of up-casting or
down-casting or whatever, it just sees pointers to different structs.
That's not sufficient for any type check with respect to the GLib type
system.

So, the user can pass whatever pointer to gtk_dial_get_adjustment() and
if you want to offer some sanity checking for people using
gtk_dial_get_adjustment() you use GTK_IS_DIAL().

You can make assumptions about the GLib type in your internal functions
because you know (hopefully) what arguments they receive.

> Can I consider to remove *_IS_* in codes like gtk_dial_get_adjustment or is
> it a best practice to always call such macro?

You can, of course, remove it if you do not want to offer the sanity
check.  It is a best practice to always call it.  This is not a
contradiction.

Regards,

Yeti



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]