Why my preprocessor directive #if is not working?

Hello friends!

First of all, YES, I already made my research but no post helped me. :confused:

I'm trying for the first time to use the preprocessor directive #if into an Arduino code, but is not working.

Below, a small piece of my code:

#define CARDSIZE 0

// more code...

#if CARDSIZE == 0

int interval = 1000;

#else

int interval = 2500;

#endif

The code always are compiled with interval = 1000, even changing the CARDSIZE value to 1 into its #define...

Can anyone help me?

byte me;

#define CARDSIZE 8

#if (CARDSIZE == 0)
  int StackSize = 1000;
#else
  int StackSize = 2500;
#endif

void setup()
{
  Serial.begin(115200);
//  Serial.print("CARDSIZE: ");
//  Serial.println(CARDSIZE);
  Serial.print("StackSize: ");
  Serial.println(StackSize);
}

void loop()
{
}

I get StackSize: 2500 when CARDSIZE is set to 8. I get StackSize: 1000 when CARDSIZE is set to 0.

I can only think to blame something that isn't shown in your shortened example. To see that this sort of thing works in general, do something like:

#define CARDSIZE 0

#if CARDSIZE == 0
#error Zero!
#else
#error Nonzero!
#endif

Adjust the value of CARDSIZE to decide how the compile fails.

1 Like

jaholmes:
I can only think to blame something that isn't shown in your shortened example.

There is a difference...
PaulS

#if (CARDSIZE == 0)

jaholmes

#if CARDSIZE == 0
#if (CARDSIZE == 0)
#if CARDSIZE == 0

Both work for me, so does suggest you are resetting 'interval' elsewhere. You could try the alternative #ifdef

#define CARDSIZE0
// more code...
#ifdef CARDSIZE0
int interval = 1000;
#else
int interval = 2500;
#endif

Thanks PaulS, your code helped me to find the right way to use the #if. Thanks