lashgar
lashgar

Reputation: 5430

Using define macro to overload array access

Problem. I got a code computing on an array. I am about to define a macro replacing every array reads with a function call. Here is an example:

For this code:

sum += a[i];

the micro should generate:

sum += function_call(a,i);

Current solution. I found that I can replace a[i] with a(i) and use the following macro:

#define a(i) function_call(a,i)

However, I prefer not to modify the original code. I just want to add macros.

Question. Can I achieve this with a clever macro definition? Any idea is highly appreciated.

Notice: I have to use C syntax.

Upvotes: 1

Views: 102

Answers (1)

user2404501
user2404501

Reputation:

No. The C preprocessor doesn't do operator overloading, no matter how clever you are.

The [] characters in your input are not inside parentheses, therefore they aren't part of a macro argument, and they aren't alphanumeric characters so they aren't part of a macro name. Anything that's not a macro name or a macro argument is going to be passed through by the preprocessor. The preprocessor doesn't even know that '[' and ']' are a matching pair.

Upvotes: 2

Related Questions