Why is it better to use Glib data types (e.g. `gint` instead of `int`)? [duplicate]
Asked Answered
P

2

17

Possible Duplicate:
Why does glib redefine types?

In the GTK+ 2.0 tutorial, I can read here the following statement about data types:

There are a few things you probably noticed in the previous examples that need explaining. The gint, gchar, etc. that you see are typedefs to int and char, respectively, that are part of the GLib system. This is done to get around that nasty dependency on the size of simple data types when doing calculations.

I don't understand the last part of this explanation. Why is it better to use Glib data types?

Plead answered 11/12, 2012 at 13:21 Comment(0)
F
13

As the tutorial mentions, it's to ensure portability. When building code that uses glib on a new system you'd only have to modify the header file with the typedefs, not the code that uses those types.

The C99 standard added fixed-width types (int8_t, uint32_t, etc) which would make the glib types obsolete, but glib predates the C99 standard which probably is the reason why it has its own set of types.

Fitch answered 11/12, 2012 at 14:1 Comment(4)
Here is what I've understood... gint and gchar for example are just useless for portability. Only gint32 and every fixed size data types added by Glib were interesting before the C99 standard because they assure variables to have a minimum required size. Am I right ?Plead
You might be right. Though it's possible that people relied on e.g. gint to be a certain size, or at least 32 bits or something like that. The point being that it's easier to change a single typedef to meet any such requirements rather than changing every single place in your code where you use ints.Fitch
You are right, gint and gchar are not defined to be a certain size and so there is no reason to use them. See also the comment here: #2800810Hillis
In case anyone comes across this in the future: Glib has deprecated sized integer types in favor of C99 stdint.h: gitlab.gnome.org/GNOME/glib/-/issues/1484Kill
B
5

C data types are highly platform and implementation specific for example int is usually the size of a general-purpose register, char has as much bits as a byte has, long only means not smaller than int (but at least 32-bit) short int is at least 2 bytes but doesn't require to actually be smaller than int

So, using some short properly named variables is beneficial to portability.

And as the GTK 2.0 tutorial puts it:

A good example is "gint32" which will be typedef'd to a 32 bit integer for any given platform, whether it be the 64 bit alpha, or the 32 bit i386. The typedefs are very straightforward and intuitive. They are all defined in glib/glib.h (which gets included from gtk.h).

edit: As Michael said the C99 standard makes them obsolete by providing new types

Brookebrooker answered 11/12, 2012 at 14:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.