Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define multiple #defines with same value

Tags:

c++

c

I have a few things that I want to #define. Those are IN, OUT, ON, OFF, UP, and DOWN. I want the IN, ON, and UP to be a '1', and the rest '0'. Is there a way I can do something similar to this:

#define IN, ON, UP        1
#define OUT, OFF, DOWN    0

I know I can #define each on their own line, but I'm looking for a bit of compactness...

Edit:

Thanks for all the responses. The reason for these #defines are that they are for states. In my code I have stuff like this:

TRISBbits.TRISB5 = IN; if(PORTBbits.RB10 == ON) and if(condition){someFlag = UP;}

I should have clarified my usage of the #define statements.

like image 543
KZ5EE Avatar asked Feb 06 '26 02:02

KZ5EE


2 Answers

I know I can #define each on their own line, but I'm looking for a bit of compactness...

No, you'll need to #define each macro separately.

Macros are pretty simple -- the name comes first, and whatever else is on the line is the value. The compiler simply substitutes the value for the name wherever the name appears.

like image 140
Caleb Avatar answered Feb 07 '26 19:02

Caleb


You can only #define one item per line.

But please consider not using #defines at all. A naieve approach would be to use static consts:

static const bool In = true, On = true, Up = true;
static const bool Out = false, Off = false, Down = false;

A better approach would be to out these in an unnamed namespace:

namespace
{
    const bool
        In = true,
        On = true,
        Up = true,
        Out = false,
        Off = false,
        Down = false;
};     

This is superior than the static consts because anything in an anonymous namespace is effectively visible in the current translation unit only. In other words, it won't pollute the global namespace.

Another alternative is to use enums:

enum
{
  In = 1,
  On = 1,
  Up = 1,
  Out = 0,
  Off = 0,
  Down = 0
};

This is either superior or inferior to either of the two alternatives above depending on how you want to use it. You can't take the address of an enum, for example.

like image 36
John Dibling Avatar answered Feb 07 '26 19:02

John Dibling