On 19 Nov 2002, Sven Neumann wrote: > Hi, > > Lars Clausen <[EMAIL PROTECTED]> writes: > >> After changing Dia's code to have more static type checking, I'm getting >> a number of errors about invalid casts from NULL. But surely NULL can >> be any type, so any cast of it should be valid. > > surely you can cast NULL to any type but you are using type-checking > casts here. These casts are supposed to guarantee that the variable > points to a valid GObject of a specific GType. This can't possibly work > with a NULL pointer.
Hmmm... looking at the GObject docs, G_OBJECT() says 'Cast a GObject or derived pointer into a (GObject*) pointer'. I would say that since NULL is a GObject pointer that points to nothing, we shouldn't get any warnings for casting it. NULL is in fact a pointer of any pointer type that points to nothing. Also, note that this means that GTK_WIDGET(gtk_item_factor_get_item(...)) will cause a warning on the legal NULL return, even though we're casting to the exact return type. Messy. >> The function in question here is gtk_item_factory_get_item(), which >> despite always returning NULL or a GtkMenuItem* has a return type of >> GtkWidget*. After some nasty bugs caused by the lack of static type >> check for this, I decided to make better use of the compilers >> typechecking. But if I say >> GTK_MENU_ITEM(gtk_item_factory_get_item(...)), I get warnings whenever >> it returns NULL. Having to check for NULL before casting would be >> cumbersome. > > gtk_item_factory_get_item() returns a GtkWidget pointer so the return > value should be assigned to a GtkWidget pointer as well. If you later > need to use the widget as a GtkMenu, you should do the type-checking > cast there (after checking that it is non-NULL). So why does gtk_item_factory_get_item() return a GtkWidget*, when the description indicates that it will always be a GtkMenuItem*? (Or NULL, but you can't say that NULL is a valid GtkWidget object either.) In general, functions ought to return the most specific type possible, to make the greatest use of the compile-time type checks. Using GtkWidget* for the return type of methods where you know the returned object is more specific is like using void* instead of <type>*. It provides a little programming ease at the cost of some hard-to-trace bugs. -Lars -- Lars Clausen (http://shasta.cs.uiuc.edu/~lrclause)| H�rdgrim of Numenor "I do not agree with a word that you say, but I |---------------------------- will defend to the death your right to say it." | Where are we going, and --Evelyn Beatrice Hall paraphrasing Voltaire | what's with the handbasket? _______________________________________________ gtk-list mailing list [EMAIL PROTECTED] http://mail.gnome.org/mailman/listinfo/gtk-list
