#define in C, legal character

  • A+

There is a C structure

struct a { int val1,val2; } 

I have made changes to the code like

struct b {  int val2; } struct a { int val1; struct b b_obj; } 

Now, usage of val2 in the other C files is like a_obj->val2; I want to replace it's declaration usage and there are a lot of them so I have defined a macro in the header file where the struct a is defined as follows :-

#define a_obj->val2 (a_obj->b_obj.val2) 

It's not working. Is -> illegal in #define? could someone please tell me where am I wrong?

Edit as suggested by @Basile - It's a legacy source code, a very huge project. Not sure of LOC. I want to make such changes because I want to make it more modular. For example I want to group similar fields of the structure under a same name and that's the reason I want to create another struct B with fields which are related to B feature and also common to A. I can't use Find Replace feature of other text editors, I am using VIM.


This kind of macro magic will get you into trouble soon,
because it is making your source code unreadable and brittle (credits Basile for the phrasing).
But this should work for what you describe.

struct b {  int val2m; } struct a { int val1; struct b b_obj; }  #define val2 b_obj.val2m 

The trick is to give the actual identifier inside the struct declaration a new name (val2m), so that the name all the other code uses can be turned into a magic alias,
which then can contain the modified access to take a detour via the additionally introduced inner struct.

This is only a kind of band-aid for the problematic situation of having to change something backstage in existing code with many references. Only use it if there is no chance of refactoring the code cleanly. ("band-aid", appropriate image by StoryTeller, credits).

I explicitly recommend looking at Basiles answer, for a cleaner more "future-proof" way. It is the way to go to avoid the trouble I predict with using this macro magic. Use it if you are not forced by very good reasons.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: