PHWinfo banniere

Titres
PORTAIL ANNUAIRE ARTICLES COMPARATEUR HÉBERGEURS DEVIS FORUMS RÉDUCTEUR D'URL
Précédent   PHWinfo > Autres forums > Forum Programmation & Conception > comp.lang.c > Variable declaration inside a switch statement.
S'inscrire FAQ Membres Recherche Messages du jour Marquer les forums comme lus
Variable declaration inside a switch statement.

Réponse
 
LinkBack Outils de la discussion
Vieux 21/10/2007, 12h00   #1
Srinu
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Variable declaration inside a switch statement.

Hi all,

If we compile the below piece of code, it gets compiled. But gives
weird result.

switch(x)
{
int y=2;

case 1:
printf("%d", y);
}


What, if any, the C standard says about it?

Srinu.

  Réponse avec citation
Vieux 21/10/2007, 12h27   #2
Dave Dunfield
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

>Hi all,

>If we compile the below piece of code, it gets compiled. But gives
>weird result.


>switch(x)
>{
>int y=2;


>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

----------------------------------------------------------------------------------------------
PS: GCC warns of "unrechable code at beginning of switch statement"

--
dave06a@ Low-cost firmware development tools: www.dunfield.com
dunfield. Classic computer collection: www.classiccmp.org/dunfield
com Some stuff I have for sale: www.dunfield.com/sale

  Réponse avec citation
Vieux 21/10/2007, 12h40   #3
abhy
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

On Oct 21, 4:00 pm, Srinu <sinu.nayak2...@gmail.com> wrote:
> Hi all,
>
> If we compile the below piece of code, it gets compiled. But gives
> weird result.
>
> switch(x)
> {
> int y=2;
>
> case 1:
> printf("%d", y);
>
> }
>
> What, if any, the C standard says about it?
>
> Srinu.


Can u tell me what weird results it gives ?

  Réponse avec citation
Vieux 21/10/2007, 18h41   #4
CBFalconer
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

Srinu wrote:
>
> If we compile the below piece of code, it gets compiled. But
> gives weird result.
>
> switch(x) {
> int y=2;
>
> case 1: printf("%d", y);
> }
>
> What, if any, the C standard says about it?


What you fail to realize is that initialization of an automatic
variable requires the generation of code. That code has to go
where the "int y = 2;" statement appears. There is no reason for
the switch statement to transfer control to that code, so y is
uninitialized (or worse) when the printf is executed.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>



--
Posted via a free Usenet account from http://www.teranews.com

  Réponse avec citation
Vieux 21/10/2007, 18h43   #5
CBFalconer
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

abhy wrote:
> Srinu <sinu.nayak2...@gmail.com> wrote:
>

.... snip ...
>
>> What, if any, the C standard says about it?

>
> Can u tell me what weird results it gives ?


u hasn't posted in c.l.c for some time.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>


--
Posted via a free Usenet account from http://www.teranews.com

  Réponse avec citation
Vieux 21/10/2007, 19h32   #6
Keith Thompson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

abhy <abhijitkrao283@gmail.com> writes:
> On Oct 21, 4:00 pm, Srinu <sinu.nayak2...@gmail.com> wrote:
>> If we compile the below piece of code, it gets compiled. But gives
>> weird result.
>>
>> switch(x)
>> {
>> int y=2;
>>
>> case 1:
>> printf("%d", y);
>>
>> }
>>
>> What, if any, the C standard says about it?

>
> Can u tell me what weird results it gives ?


Please don't use silly abbreviations like "u" for "you". This isn't a
chat room. Take the time to spell out simple words.

Yes, showing the actual questionable output is almost always a good
idea. In this particular case, though, it's unnecessary. The
variable y is uninitialized when it's printed; any output is possible.
(Actually, the behavior is undefined, so in principle *anything* is
possible, but it will most likely print some arbitrary value of type
int.)

--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
  Réponse avec citation
Vieux 22/10/2007, 08h32   #7
karthikbalaguru
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

On Oct 21, 4:00 pm, Srinu <sinu.nayak2...@gmail.com> wrote:
> Hi all,
>
> If we compile the below piece of code, it gets compiled. But gives
> weird result.
>
> switch(x)
> {
> int y=2;
>
> case 1:
> printf("%d", y);
>
> }
>
> What, if any, the C standard says about it?
>


This is a famous question in interviews

A switch statement never enters at the top.
So, your initialization never gets executed.

Karthik Balaguru

  Réponse avec citation
Vieux 22/10/2007, 21h45   #8
abhy
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

On Oct 21, 10:43 pm, CBFalconer <cbfalco...@yahoo.com> wrote:
> abhy wrote:
> > Srinu <sinu.nayak2...@gmail.com> wrote:

>
> ... snip ...
>
> >> What, if any, the C standard says about it?

>
> > Can u tell me what weird results it gives ?

>
> u hasn't posted in c.l.c for some time.
>
> --
> Chuck F (cbfalconer at maineline dot net)
> Available for consulting/temporary embedded and systems.
> <http://cbfalconer.home.att.net>
>
> --
> Posted via a free Usenet account fromhttp://www.teranews.com


Hi Karthik

I didn't get the meaning of your answer " A switch statement never
enters at the top. "..?
Please explain.

  Réponse avec citation
Vieux 22/10/2007, 21h56   #9
Eric Sosman
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

abhy wrote On 10/22/07 16:45,:
> [...]
> I didn't get the meaning of your answer " A switch statement never
> enters at the top. "..?
> Please explain.


He means this:

switch (x) {
/*
* Nothing here will ever be executed,
* because `switch' proceeds directly
* to the chosen case or to the end of
* the entire block if no case is chosen.
*/

case 42:
/*
* This is the first piece of code that
* the `switch' can ever execute.
*/
...
}

--
Eric.Sosman@sun.com
  Réponse avec citation
Vieux 23/10/2007, 07h28   #10
Srinu
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

Dear friends,

Thanks a lot for your valuable suggestions.

Srinu.

  Réponse avec citation
Vieux 04/11/2007, 23h02   #11
David Thompson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable declaration inside a switch statement.

On Sun, 21 Oct 2007 11:27:00 GMT,
Dave.Dunfield@use.techsupport.link.on.my.website (Dave Dunfield)
wrote:

> >switch(x)
> >{
> >int y=2;

>
> >case 1:
> >printf("%d", y);
> >}


> 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.
>

Right.

> 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.
>

IPSYM the maximum of the amounts required by any 'stack' of nested and
hence concurrently alive subblocks, each of which (per subblock and
hence stack) is fixed at compiletime, except VLAs as below.

> 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!
>

.... in C89. In C99 declarations can occur after statements, and the
initializations occur (only) when the declaration is 'executed'.

Except for VLA types. They may be and probably are _allocated_ (only)
when the declaration is 'executed', and jumping 'past' the declaration
(formally, into the scope) is a Constraint Violation.

- formerly david.thompson1 || achar(64) || worldnet.att.net
  Réponse avec citation
Réponse


Outils de la discussion

Règles de messages
Vous ne pouvez pas créer de nouvelles discussions
Vous ne pouvez pas envoyer des réponses
Vous ne pouvez pas envoyer des pièces jointes
Vous ne pouvez pas modifier vos messages

Les balises BB sont activées : oui
Les smileys sont activés : oui
La balise [IMG] est activée : oui
Le code HTML peut être employé : non
Trackbacks are oui
Pingbacks are oui
Refbacks are oui


Fuseau horaire GMT +1. Il est actuellement 02h42.


Édité par : vBulletin® version 3.7.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0 RC5 Tous droits réservés.
Version française #16 par l'association vBulletin francophone
PHWinfo est un site Éducation Sans Frontières ©2000-2008
Ad Management by RedTyger
©Tous droits réservés par les parties respectives
Page generated in 0,20490 seconds with 19 queries