I am implementing a vector library.
I planned to do it in the header .h
file only.
// vector.h
typedef struct vec2_t {
float x;
float y;
} vec2;
Consider I will implement the add
function, I am having 2 choices:
// also in vector.h
// 1st option
static inline vec2 add(vec2 lhs, vec2 rhs) {
vec2 v;
v.x = lhs.x + rhs.x;
v.y = lhs.y + rhs.y;
return v;
}
// usage in 1st option
vec2 v3 = add(v1, v2);
// 2nd option
static inline void add(const vec2 * const lhs, const vec2 * const rhs, vec2 * const rt) {
rt->x = lhs->x + rhs->x;
rt->y = lhs->y + rhs->y;
}
// usage of 2nd option
vec2 ret;
add(&v1, &v2, &ret);
So, if this is a normal function
I will go with the 2nd option.
However, in this case, the static inline
, I am not quite sure what is the appropriate way.
I learned that the inline
keyword is just a hint, not a command that the compiler needs to follow. (What's the difference between "static" and "static inline" function?)
- if the compiler decides not to inline, the 2nd option seems to be a good choice (especially if that is
vec3
vec4
). - if the compiler decides to inline, the 1st option makes sense (I don't think the compiler is smart enough to substitute the pointer
->
to the member access.
).
So with that in mind, my question is:
What is the appropriate way to define a static inline function in C language?
Thank you very much!