dizcza
dizcza

Reputation: 698

C preprocessor directives operator ##

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

Upvotes: 2

Views: 85

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

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.

Upvotes: 1

Related Questions