Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

something about #define syntax in C

Tags:

c

could any one explain what does

#define something (54)

mean? Why 54 is inside a bracket?

like image 536
fiftyplus Avatar asked Dec 20 '22 18:12

fiftyplus


2 Answers

#define something (54) tells the C pre-processor to replace any text matching "something" with "(54)" before the code is actually compiled.

The reason you will often see the use of ( ) around a #define is that in some cases it prevents the replaced text from having adverse or undefined behavior when the #defined text is replaced into a larger expression. Such adverse effect might be the changing of operator precedence etc..

like image 50
Chimera Avatar answered Dec 24 '22 01:12

Chimera


It is in general a good idea to put any #define statement inside parenthesis. This is a good habit, and most daily programmers adhere to good habits.

For instance:

#define TWO_PLUS_ONE    2 + 1

if I use it like this:

3 * TWO_PLUS_ONE

I would expect to see the answer as 9, however due to operator precedence, the calculated answer would be 7. There are dozens of corner cases you could find like this (see http://www.gimpel.com/html/bugs.htm). This is why C++ programmers scream, "Macros are evil!". But we are C programmers, we are elite, we ain't scared.

The same example:

#define TWO_PLUS_ONE    (2 + 1)

This will give the expected result in all situations.

Most programmers want their practices to apply in all situations, so it is easy to remember, easy to practice and easy to do. So in the simple case of

#define SOMETHING    (54)

Just do it. It is a good idea. Learn to be part of the team, they are trying to help you. BTW, next they will say, "it should really be (54u)"

like image 30
Josh Petitt Avatar answered Dec 24 '22 00:12

Josh Petitt