Why are kuid_t and similar data types of type struct?

Viewed 72

In the Linux kernel source, kuid_t is defined as a typedef struct that contains a single uid_t variable val. What's the reason to define kuid_t as a structure instead of a single typedef uid_t kuid_t? I see it as a bit overhead to declare a structure just for a single variable, and to access it you need to use kuid_t.val:

typedef struct {
    uid_t val;
} kuid_t;

Instead of the following, which is pretty much the usual thing you would do:

typedef uid_t kuid_t;
1 Answers

Converting my comment into an answer.

I'm not a party to the official reasoning of the kernel developers, but…

Using a structure (typedef struct { uid_t val; } kuid_t;) to encapsulate the UID ensures you don't pass a (hypothetical?) kgid_t (for GID) where a kuid_t is wanted and vice versa. It improves the type safety of the kernel code by avoiding implicit conversions between integer types.

If the code used simple numerical types like typedef uid_t kuid_t; and typedef gid_t kgid_t;, there's a good chance that the underlying type for uid_t and gid_t is the same, so you could easily pass a value of uid_t where the required type is gid_t or vice versa, and the compiler cannot detect the logic problem.

Don't forget: a typedef is an alias for an existing type name, not a new type. Also, simple structures like the kuid_t shown in the question can be passed to functions by value just as efficiently as primitive types — but with the extra type checking.

Related