08-07-2008 03:09 PM
08-08-2008 04:22 PM
05-06-2013 11:27 AM
Sorry to resurrect a very old post. But I too have run into a situation where an entire else condition block was not executed. It's as if the compiler has optimized it away? But that doesn't make much sense to me.
In my case, I have braces in my else block, because I'm executing compound statements. But I did not have braces in my if / else if preceding blocks. Here's what I did initially:
if (fVoltage < vSettingLo || fVoltage > vSettingHi) if (++unitRetry[slot] >= MAX_UNIT_TRIES) { GoStopUnit(bank,unit,VFAIL); // now fail the unit unitRetry[slot] = 0; // reset the retry counter } else if (fCurrent < iSettingLo || fCurrent > iSettingHi) if (++unitRetry[slot] >= MAX_UNIT_TRIES) { GoStopUnit(bank,unit,IFAIL); // now fail the unit unitRetry[slot] = 0; // reset the retry counter } else { // update the meters SetCtrlAttribute(panel,GetCtrlArrayItem(serialArray,slot),ATTR_TEXT_COLOR,VAL_DK_GREEN); SetCtrlAttribute(panel,GetCtrlArrayItem(snArray,slot),ATTR_TEXT_COLOR,VAL_DK_GREEN); SetCtrlAttribute(panel,GetCtrlArrayItem(fvoltageArray,slot),ATTR_TEXT_BGCOLOR,VAL_DK_GREEN); SetCtrlAttribute(panel,GetCtrlArrayItem(fcurrentArray,slot),ATTR_TEXT_BGCOLOR,VAL_DK_GREEN); }
In my view, since the if and the else if conditions on executed one line (a nested if block), that shouldn't have affected my last else block. But it did! This is repeatable. The last else block gets ignored. The solution is to put braces around the nested if blocks in the first if and in the next else if conditions. Then my last else gets left in by the compiler.
Odd!
05-06-2013 12:15 PM
Well, it seems logic to me, instead! Let me rephrase your code a little:
if ( -1- ) if ( -2- ) { } else if ( -3- ) if ( -4- ) { } else ( -5- ) { }
It seems to me that regardless the indentation, if #3 is treated as the else condition of if #2. Similarly, condition #5 is treated as the else of if #4. That is: if the signal is within boundaries, the code does nothing!
A proper set of braces on ifs #1 and #3 permits to execute block #5 is signals are correct.
05-06-2013 02:30 PM
Yes, Roberto, you are correct. Apparently, this is a revelation of my lack of ANSI C knowledge. 😉
Somewhere along my professional life, I had made the assumption that the line immediately following a conditional statement was executed if that conditional resolved TRUE. And compound statements were supported with braces. For instance, this is correct given this example:
if (i) temp++; else if (j) temp--;
As you said, indentations are for humans. But now I see the logic problem with my assumption. How does the compiler know which if goes with which else?