I'm not sure if this would work but I thought I'd bounce this off you guys anyway.
So, I have an if/elseif/else statement and cut out the else part to cut down on code space. I thought about leaving it in and only compiling this section if I set a certain bit using #define statements. For example, my code started off like this:
unsigned char variable; if(variable==1) { //Condition 1 } else if(variable==2) { //Condition 2 } //else //{ // //Condition 3 //}
I wanted to include Condition 3, but only if I set the #define bit so now my code looks like this:
#define definecondition 1 unsigned char variable; if(variable==1) { //Condition 1 } else if(variable==2) { //Condition 2 } #if(definecondition==1) { else { //Condition 3 } } #endif
It turns out the way I am trying to implement this does not compile due to the else statement currently within a separate if statement. Now, I can still do this by using:
#if(definecondition==1) { if((variable!=1)&&(variable!=2)) { //Condition 3 } } #endif
but I was curious if there was a way to use the #define statement to still be able to work with the previous if statement (as demonstrated above). I tried using a #else statement but that didn't work either (it was worth a shot). Any other methods that might work out? I can force it to work using my method but if there's a better way, I'd like to know.
Thanks, guys!
Yes - #if or #ifdef before last "else { ... }" or before last "} else { xxx " works.
I actually think I found a way that works:
#define definecondition 1 unsigned char variable; if(variable==1) { //Condition 1 } else if(variable==2) { //Condition 2 } else { #if(definecondition==1) { //Condition 3 } #endif }
But don't you find it better with this?
#define definecondition 1 unsigned char variable; if(variable==1) { //Condition 1 } else if(variable==2) { //Condition 2 } #if(definecondition==1) else { //Condition 3 } #endif
I would, but that appears to be exactly the same code I placed in my first post and it wouldn't compile. What's the difference besides a few brackets?
Those extra brackets are what caused the compilation failure.
Wow. You are correct about that. Out of curiosity, what is it those extra brackets do that cause it to fail?
They introduced a "naked else" without a corresponding "if".
When you have problems like this due to the preprocessor, you need to examine the preprocessor output. Then you will see the code exactly as the compiler sees it - after preprocessing.
In Keil C51, use the PREPRINT option:
http://www.keil.com/support/man/docs/c51/c51_preprint.htm
www.8052.com/.../29152