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

风格不统一 提交于 2019-12-06 17:21:43

问题


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?


回答1:


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.




回答2:


C data types are highly platform and implementation specific for example int is the size of the register, char has as much bits as a byte has, long only means not smaller than int 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



来源:https://stackoverflow.com/questions/13821332/why-is-it-better-to-use-glib-data-types-e-g-gint-instead-of-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!