Lenn
Lenn

Reputation: 1

How to use the "define" keyword?

I am new to C coding. I have come across an example code and I have trouble understanding the syntax:

//Turn ON MOSFET.
#define SWITCH_STATE_ON     (1)
//Turn OFF MOSFET.
#define SWITCH_STATE_OFF    (0)

Why do we have the brackets around "1" and "0"? I would have written the above but without brackets. Is this a mistake?

//Turn ON MOSFET.
#define SWITCH_STATE_ON     1
//Turn OFF MOSFET.
#define SWITCH_STATE_OFF    0

Thank you!

Upvotes: 0

Views: 82

Answers (4)

John Bode
John Bode

Reputation: 123598

It's to guard against precedence issues if your macro expands to an arithmetic expression or something like that. For example, assume the macro

#define SQR(x) x * x

If you write

x = SQR(1 + 2);

that would expand to

x = 1 + 2 * 1 + 2;

which isn't what you want - what you want is

x = (1 + 2) * (1 + 2);

so you would define the macro as

#define SQR(x) (x) * (x)

or better yet,

#define SQR(x) ((x) * (x))

For a numeric literal like what you have, it doesn't really make a difference. It doesn't hurt, but it doesn't add anything, either.

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 224546

In C, after preprocessor macros are replaced, the resulting source code is analyzed according to C grammar. This means that if somebody defines a macro:

define Foo 3+7

and then uses it:

printf("%d\n", 2*Foo);

the result of macro replacement will be printf("%d\n", 2*3+7);. Then this will be interpreted as printf("%d\n", (2*3)+7;, which will print “13”. To avoid this, macros that are intended to be used as expressions are commonly written with parentheses surrounding the replacement list:

#define Foo (3+7)

Then the result of replacement will be printf("%d\n", 2*(3+7));, which will print “20”.

In the case where the replacement list is a single token, such as 0 or 1, the parentheses are not necessary, as this mixing with neighboring tokens cannot occur. However, many people do it as a habit.

Upvotes: 3

fjm
fjm

Reputation: 21

Using Xcode, v11.3, I was able to compile (without errors) using both no brackets around the 0 and 1 digits as well as using brackets around both digits.

So, after entering "...#define MOSFET_ON 1 and #define MOSFET_OFF 0, and also

#define MOSFET_ON (1) , #define MOSFET_OFF (0), both worked. I'm not sure why, unless it's a specific IDE you are using, and, or compiler?

Upvotes: 0

jonathano88
jonathano88

Reputation: 21

According to this:

Syntax

The syntax for creating a constant using #define in the C language is:

 #define CNAME value

OR

 #define CNAME (expression)

which means that 1 is not a value but an expression. As you can't use numbers as variable names i'd assume in this case 1 means 1 and it's pointless to use parentheses.

Upvotes: -1

Related Questions