uint vs. unsigned int - Why not typedef uint?

Viewed 739

I was wondering if there are any side-effects defining uint.

typedef unsigned int uint;
3 Answers

Reading code like that is pain in the neck.

If you want to save some typing then use unsigned. That's shorthand for an unsigned int and is standard C. Standard C is readable C.

If you are attempting to standardise the sizes and ranges of integral types, then use the ones in <stdint.h> instead.

You might be tempted to define uint as typedef unsigned int uint; to have the type unsigned int defined with a single word, for various reasons:

  • for stylistic reasons, because of local tradition.
  • out of consistency with types defined in <stdint.h> that all use int and uint for the signed and unsigned types (ex: int8_t and uint8_t).
  • to have all basic types defined with a single word, as might be required for token pasting macros. Of course unsigned would fit this need, but ulong would still be useful.

I can see these potential problems:

  • reading your code, some people might not know what type uint is supposed to be, or might wonder if uint is defined as something unexpected.
  • if you compile on some systems where this type is already defined in standard header files or some library's header files, you would get a compile error, thereby making your code less portable.

Also if you are a time traveller, stop by Dennis Ritchie's office in Murray Hill sometime late 1974 when C was described by this C Reference Manual, before unsigned was even invented and suggest uint as an alternative. I'm sure Ken Thomson would back you. And also tell Stu Feldman to avoid TABs :)

The negative effect is stylistic, namely that making your own home-brewed types turns your code unreadable. Nobody knows what "uint" is, so using such a home-made type is far worse practice than using unsigned int.

Instead of this, you should use the standardized integer types from stdint.h.

Related