Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does it make sense to typedef basic data types?

A company's internal c++ coding standards document states that even for basic data types like int, char, etc. one should define own typedefs like "typedef int Int". This is justified by advantage of portability of the code. However are there general considerations/ advice about when (in means for which types of projects) does it really make sense? Thanks in advance..

like image 784
User 154806 Avatar asked Feb 09 '11 10:02

User 154806


2 Answers

Typedefing int to Int offers almost no advantage at all (it provides no semantic benefit, and leads to absurdities like typedef long Int on other platforms to remain compatible).

However, typedefing int to e.g. int32_t (along with long to int64_t, etc.) does offer an advantage, because you are now free to choose the data-type with the relevant width in a self-documenting way, and it will be portable (just switch the typedefs on a different platform).

In fact, most compilers offer a stdint.h which contains all of these definitions already.

like image 159
Oliver Charlesworth Avatar answered Sep 24 '22 23:09

Oliver Charlesworth


That depends. The example you cite:

typedef int Int;

is just plain dumb. It's a bit like defining a constant:

const int five = 5;

Just as there is zero chance of the variable five ever becoming a different number, the typedef Int can only possibly refer to the primitive type int.

OTOH, a typedef like this:

typedef unsigned char byte;

makes life easier on the fingers (though it has no portability benefits), and one like this:

typedef unsigned long long uint64;

Is both easier to type and more portable, since, on Windows, you would write this instead (I think):

typedef unsigned __int64 uint64;
like image 38
Marcelo Cantos Avatar answered Sep 23 '22 23:09

Marcelo Cantos