Anoop wrote:
Hi guys
i have a piece of code
main()
{
switch(...)
{
case 1:
{
char a[200];
}
case 2:
{
char a[200];
}
case 3:
{
char a[200];
}
}
}
now the question is what will be the memory allocated when the program
enters his function to the first statement switch(...)
1. will it be 600 bytes - sum of all local variables
2. or the allocation will be done depending upon execution path and in
whichever case it goes.
Whatever is the answer? Kindly give proper reasons why will that
happen and also any compiler dependebt issues.
Thanx in Advance
Anoop
1. The declaration and definition of the arrays is local to the block
it is contained in. When execution leaves the block, the local
variables disappear. The block is defined between the open and
close braces: '{' and '}'.
2. Since there is no 'break' after any of the cases, the torment that
the memory allocation goes through depends upon the switch value.
In the above case, if the switch variable evaluates to 1, there
will be 3 times that an array is locally allocated and removed.
3. The compiler may choose not to allocate the array since it is not
used anywhere else in the block that it was defined in.
4. Since there is no code in any of the case statements, the compiler
may decide to not translate the switch statement (an optimization),
thus no arrays would be allocated.
5. Defining variables in a case statement or block and using them
outside of the switch statement is bad karma. Better karma is
to define variables before the switch statement, then process
them in the case(s) and maybe also after the switch statement.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library