klutt
klutt

Reputation: 31376

What is the reason that some functions in standard library just appear to be wrappers or aliases?

When I have looked into the source of glibc, I sometimes stumbles over functions that are wrappers that does nothing and only works as an alias. For example:

int
rand (void)
{
  return (int) __random ();
}

What is the reason for things like this? Why not just take the body of __random() and put it in rand()?

Upvotes: 1

Views: 105

Answers (1)

Myst
Myst

Reputation: 19221

This is a very case specific question as there are a variety of reasons for such a behavior. One answer cannot cover all the reasons for all the cases.

For example, some compilers contain a variety of system specific "builtin" implementations, so the source / header files simply tell the compiler to place their implementation in there.

Another reason would be to type cast from a more general function to a standard conforming type.

Some functions contain repeated functionality (think printf vs. fprintf(stdin,...), and using wrappers is a simple way to keep the code more DRY.

Specifically, __random returns a long int and needs to be converted to int (which may or may not be the same, depending on your system).

In addition, __random reuses functionality in __random_r, but adds a lock to make the functionality thread safe.

Reusing the same functionality with minor variations (a global thread-safe state) keeps the code more DRY.

Upvotes: 6

Related Questions