2

I want to create a function void vec2_from_vec3(vec2 res, vec3 from) in pure C, using operator ## like so:

#define MAGIC_MACROS(n) \
void vec##(n-1)##_from_vec##n##(vec##(n-1) res, vec##n from);

but compiler woudn't let it. Is it possible?

Inspired by https://github.com/datenwolf/linmath.h/blob/master/linmath.h

1 Answer 1

1

The preprocessor won't evaluate/compute n-1, it will just expand it. Ex: 3-1, so string concatenation won't work

(a modern compiler does it but it's already too late)

You can always do that which isn't that bad already:

#define MAGIC_MACROS(n1,n2) \
void vec##n1##_from_vec##n2##(vec##n1 res, vec##n2 from)

and use as:

MAGIC_MACROS(2,3);

Note that you shouldn't end your macros with ;, so it's homogeneous with function calls and doesn't break editor auto-indentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, I want to create typedef int16_t vec3i[3] with # define INT_BITS 16 and then # define LINMATH_H_DEFINE_VECI(n,b) typedef int##b##_t vec##n##i[n]; and call LINMATH_H_DEFINE_VECI(3, INT_BITS). But it changes to typedef intINT_BITS_t vec3i[3]. It's not possible too, right?
no for same reason: preproc only replaces once. You have to pass (3, 16)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.