Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

c - Is it "proper" to define macros for use in a single function

I'm not asking if it's possible to #define a macro inside a function. I understand that it is possible and that macros are preprocessing mechanisms that are almost copy-paste (to an extent). What I'm asking is are there broad reasons to avoid making a macro for use in a single function or is it simply up to the codebase maintainers as to what they decide is good style?

Here is a contrived example similar to my usecase:

int main() {
   /* ... */
   
   #define POS(x, y) grid_array[width*(y) + (x)]
   
   /* Use POS(x, y) in this function */
   
   #undef POS
   
   /* ... */
}

Another way to put the question is: Would other C developers nod their head in understanding or shake their head in distain?

Edit:

This is not a duplicate of the question "Macro vs function." I understand (some of) the differences between the two, e.g. MIN(a, b) (a)>(b)?(b):(a) evaluates a and b twice. I'm asking if it is good practice to use a macro for a single function.

The answer (and comments) pointed out that my simple example doesn't merit using a macro. Though my actual use case is not that simple, I have to agree. The "saved typing" doesn't merit convoluted code.

Here's my actual use case if you were curious:

/* array represents a graph with max degree 2. These operations are domain specific. */
#define CONNECT(a, b, i) {array[8*(a) + i] = b; array[8*(b) + (i+4)%8] = a;}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The primary purpose of any programming language, outside of just hex values, is to make the intent and implementation more obvious to the reader. Programs are meant to be read by people, and translated by machines.

To that extent, if POS(x,y) merely saves you typing, that might be of value to the reader, but you should consider the reader more than the writer. Any worthwhile program will have many more readers than writers, so your obligation as a writer is to lessen their load.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...