can I put a #define statement inside a if statement like below?

Can I put define statements inside an if block as below?
What will be printed? I want 2 to be printed.

int x = 1;

if (x == 1){
Serial.print("x = 1");
#define y 2
}
if (x == 2){
Serial.print("x = 2");
#define y 3
}

Serial.print(y);

no. y is a preprocessor symbol, not an actual variable.

I figured this was the case. My code above did not work as expected.

From a syntax standpoint, there is nothing wrong with that, except I believe #defines MUST start in column 1. From a functional standpoint, it will NOT do what you expect, as the second #define will ALWAYS over-ride the first #define, regardless of which path is taken through the if/else. From a programming style standpoint, it is extremely poor, and a mis-use of #define to do something that is FAR better done in a number of other ways.

Getting "clever" in code is, more often than not, a recipe for creating very hard-to-find bugs.

Regards,
Ray L.

#define is for constants. Things known at compile time that can't change during run time. There are a whole set of pre-processor functions that you can use to conditionally write your code, but without knowing what it actually is that you're after it's impossible to tell if that is what you should be doing or if what you really need is an ordinary variable here.

I thought I could save variables and storage by putting the defines inside the if but I was wrong.

I know better now.

Thanks all.

Well if you know the value of x at compile time you can, it just uses a different type of statement.

RayLivingston:
I believe #defines MUST start in column 1.

Nope. There can be whitespace both before and after the #.

RayLivingston:
Getting "clever" in code is, more often than not, a recipe for creating very hard-to-find bugs.

Regards,
Ray L.

Amen to that!

-jim lee