3

I'm trying to implement type-generic vector operations through C macros. My current implementation works if initialization and declaration happens on the same line, since the macro is then aware of the type of the vector:

vec2_t(char) char_vector = vec2(10, 20);         // unexpanded
struct {char x, char y;} char_vector = {10, 20}; // expanded

However, the problem is that if I then try to reassign the vector, it's no longer aware of the type, and as a result it won't compile:

char_vector = vec2(20, 30); // unexpanded
char_vector = {20, 30};     // expanded

Expanding it to char_vector = (struct {char x, char y;}) {20, 30}; would fix the problem, but this would require having to specify the type everytime the vector is reassigned. The same issue also occurs with other vector operations such as adding, etc.

Is there a way to implement this without needing to specify the type on every reassignment? I realize typeof could work here on Linux, but I'm looking for a platform-independent solution.

PandaConda
  • 3,396
  • 2
  • 20
  • 22
  • 3
    C11's generics might work here, but you'd still need a macro wrapping the assignment. Hint: that's not very intuitive, it will make your code into a kind of custom language on top of C, which simply doesn't have features like this natively. – unwind Apr 03 '17 at 09:26
  • 2
    Why not create macro or function which could called as `vec2_set(&char_vector, 20, 30)`? – user694733 Apr 03 '17 at 09:30
  • @user694733 Would that work with stack-allocated variables? If so then I like this solution. – PandaConda Apr 03 '17 at 09:31
  • 1
    If you implement it as `#define vec2_set(v, a, b) do{ (v)->x = (a); (v)->y = (b); }while(0)`, then I don't see why not. But it won't work as an initializer if that's what you mean. But do you really need same macro for initalizer and assignment? – user694733 Apr 03 '17 at 09:34
  • @unwind I think the amount of duplicated code this voids makes it an ok solution. I'm not compiling with c11 at the moment, but thanks for the input. – PandaConda Apr 03 '17 at 09:37
  • @user694733 oh right, its a macro so stack variables shouldn't be a problem. Why the loop though? – PandaConda Apr 03 '17 at 09:38
  • 1
    I guess that 'use C++' would not be good as an answer? – ThingyWotsit Apr 03 '17 at 09:38
  • @ThingyWotsit haha unfortunately not, trying to stick with C. – PandaConda Apr 03 '17 at 09:39
  • Macro or function, should not make a difference. You can take the address of stack allocated variables all the same. [do {} while(0) is simply a add additional safety to a macro.](http://stackoverflow.com/q/923822/694733). – user694733 Apr 03 '17 at 09:41
  • @user694733 Nice, thats a cool trick. if you type this up as an answer I'll accept it as the solution – PandaConda Apr 03 '17 at 09:49

0 Answers0