I'm writing a toy vector library in C to learn a bit about the language. The excerpt below shows my vector structure and two functions:
vec2_magnitude
calculates the magnitude (length) of a vectorvec2_unit
uses the magnitude to calculate the unit vector
#include <math.h>
// A fixed-length vector w/ 2 elements.
typedef struct
{
double a;
double b;
} vec2_t;
// Compute the magnitude of a vec2_t.
double vec2_magnitude(const vec2_t *vec)
{
double a2 = vec->a * vec->a;
double b2 = vec->b * vec->b;
return sqrt(a2 + b2);
}
// Compute the unit vector of a vec2_t.
void vec2_unit(const vec2_t *vec, vec2_t *unit)
{
double mag = vec2_magnitude(vec);
unit->a = (vec->a / mag);
unit->b = (vec->b / mag);
}
Currently, vec2_unit
takes two vector arguments. It performs the calculation based on the first argument, then stores its result in the second argument. I wrote the function this way so the original vector wouldn't be affected (in case it is still needed).
That being said, I'd like a way to calculate the unit vector in-place, since you may not always need the old vector (in such a situation, an in-place calculation is more convenient). I was originally going to write two functions, but noticed a clever way to achieve both functionalities using only the function shown above.
To operate non-destructively, vec2_unit
can be called like this:
vec2_t orig_vector = {1, 1};
vec2_t unit_vector;
vec2_unit(orig_vector, unit_vector);
To operate in-place, vec2_unit
can be called like this:
vec2_t orig_vector = {1, 1};
vec2_unit(orig_vector, orig_vector);
I like this solution, and it seems to work. I also understand that C is a language where many things aren't "safe", and just because you can do something doesn't mean you should. Are there any reasons something like this shouldn't be done? Are there other examples of common C functions that work in a similar way? Is there a better way to accomplish what I'm trying to do?
I appreciate all help. Feel free to comment on anything else you see as well. Thanks!