Hi all,
If we compile the below piece of code, it gets compiled. But gives
weird result.
case 1:
printf("%d", y);
}
By strange co-incidence I received this same question from a co-
worker only last week (He thought it was a compiler bug) - this
was my answer:
----------------------------------------------------------------------------------------------------
Dear Dave!
I don't think this is a serious problem (I guess we never did it)
however local variables defined inside switch brackets are not
initialized properly.
What do you think about this?
void test_test_test(void)
{
UINT c = 0;
switch(c)
{
UINT t = 30000;
case 0:
default:
printf("\r\nMust be 30000: %d",t);
break;
}
}
Hi <name removed>,
Thats a really weird thing to do, however it is NOT a bug!
From K&R-2, page 223:
"Initialization of automatic objects is performed each time the
block is entered at the top, and proceeds in the order of the
declarators. If a jump into the block is executed, these
initializations are not performed."
A switch statement is by definition a jump into it's block,
the block is never entered at the top, and therefore your
initialized never gets executed.
An automatic declaration with initialization does two things,
1) Reserve space for the variable - this is normally done
at entry to the function (the compiler works out the minimum
footprint for all blocks at compile time and generates the
reservation at function entry.
2) Code is generated to initialize the variable when the block
is entered. This logically occurs at the point in the source
code where the declaration occurs. In the case of your
switch, any other statement positioned where your declaration
is would not execute either!
Regards,
Dave