简体   繁体   中英

Need Help understanding particular define directive in C

I am a CS student and I am learning C. I have an assignment in which our instructor gave us a .h and two .c files that have code segments that require us to complete to make functions work.

In the header file he has the following #define statements:

# ifndef LT
# define LT(A, B) ((A) < (B))
# endif

# ifndef EQ
# define EQ(A, B) ((A) == (B))
# endif

for the first define, I know that LT is the "name" but I dont understand what the syntax to the right is doing. Same with the second.

It appears to me that LT is the comparison of two variables A and B and it check that A is greater then B.

Would someone please help me to understand this

these are macros.

If you have in your c code

if(LT(xx, yy))
{
   printf("xx is less than yy\n");
}

then at compile time the code is changed to

if((xx) < (yy))
{
   printf("xx is less than yy\n");
}

this is done by the preprocessor changing #defined things that it sees to their contents

Try to get a book about C and read upon the preprocessor functionalities. It is merely a syntactic replacement without semantic meaning.

The first can be read like this: If LT is not defined then introduce the preprocessor definition LT . From that point of definition on wherever the preprocessor finds the text (I don't say string on purpose here to make a point) LT with two parameters, let's say text1 and text2 , then this text LT(text1, text2) will be replaced by the ((text1) < (text2)) .

Same for the second.

Note the parentheses, they are important. Make an example of the following appearance in your code LT(x+y, z-1) and you should understand why parentheses are important here.

I can recommend K&R for learning C. It has a chapter dedicated to the preprocessor and not difficult to understand. The more you learn you'll notice that my terminology is not the best here, but for the moment try to grasp that concept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM