Log in

View Full Version : Conditional #define Statements


Ian W.
14-02-2004, 13:28
I'm rewriting the navigate.c class for our team, and I've come to an annoying problem.

I have two sensors, left and right, for each side of the robot. Depending on a switch, only one should be read. That means I can save on code, I think.

With PBASIC, a simple if statement and alias command would set "sensor" to "left_sensor" or "right_sensor" but I have no idea how to do this in C, without going into pointers (which I don't remember).

Is there any way I can make a conditional #define (or similar) statement?

Paul
14-02-2004, 14:59
Why not just have a conditional declaration?
if(your condition is meet)
{
int your_var;
}
else
{
int something else;
}

I'm probably misunderstanding you but its still worth a shot.

steven114
14-02-2004, 15:19
Why not just have a conditional declaration?
if(your condition is meet)
{
int your_var;
}
else
{
int something else;
}

I'm probably misunderstanding you but its still worth a shot.

Won't work. The declaration goes out of scope after the if block. There are two methods -

1) You know at compile time which one you want
#if IWANTVAR1
#define myVar var1
#else
#define myVar var2
#endif

//myVar now refers to var1 or var2, depending on IWANTVAR1 (which MUST be either a constant or expand to a constant)

2) You know at runtime

int myVar;
if(iWantVar1)
myVar = var1;
else
myVar = var2;

Note that way 2 only works for reading the variable, not writing. If you want something like the aliases, you either must know at compile time or deal with pointers (afaik)

I hope this is what you wanted...

Ian W.
14-02-2004, 18:14
Ah, thanks, I didn't think about doing something simple like just reassigning the variable to a temporary variable. Seeing as I only need to read, I think I can make do with that, but I'll have to fool around with it a bit.

On the other hand, it's always a good time to relearn pointers...