473,804 Members | 2,191 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why does C standard allow this declaration

Hi

Why does C allows declaration of variable inside switch block.
ex: foll prg does not gives "undeclared "b" error msg. but also does
not initialize b to 20
int a=1;
switch(a)
{
int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf( "b is %d\n",b);
break;
}

this prints some garbage.
( yeah even though i got warning msg "unreachabl e code int b = 20" why
is it declaring inside switch block but not initializing b)

Sep 20 '06 #1
18 2131
"sunny" <su*******@gmai l.comwrites:
>Why does C allows declaration of variable inside switch block.
ex: foll prg does not gives "undeclared "b" error msg. but also does
not initialize b to 20
int a=1;
switch(a)
{
int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf( "b is %d\n",b);
break;
}
>this prints some garbage.
( yeah even though i got warning msg "unreachabl e code int b = 20" why
is it declaring inside switch block but not initializing b)

Programs do not give warnings about themselves;
different compilers may give different warnings and errors.

You will probably be horrified by Duff's Device:

http://www.lysator.liu.se/c/duffs-de...l#duffs-device
http://www.catb.org/jargon/html/D/Duffs-device.html

--
Chris,
Sep 20 '06 #2
sunny wrote:
Hi

Why does C allows declaration of variable inside switch block.
ex: foll prg does not gives "undeclared "b" error msg. but also does
not initialize b to 20
int a=1;
switch(a)
{
int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf( "b is %d\n",b);
break;
}

this prints some garbage.
( yeah even though i got warning msg "unreachabl e code int b = 20" why
is it declaring inside switch block but not initializing b)

It depends on your compiler. I am using gcc and it throws following
warning message

[kokje@RocketFue l ~]$ gcc test.c -o test
test.c: In function `main':
test.c:7: warning: unreachable code at beginning of switch statement

What compiler are you using ?

Tejas Kokje

Sep 20 '06 #3

sunny wrote:
Hi

Why does C allows declaration of variable inside switch block.
ex: foll prg does not gives "undeclared "b" error msg. but also does
not initialize b to 20
int a=1;
switch(a)
{
int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf( "b is %d\n",b);
break;
}

this is an unfortunate side efect of allowing declarations at the
beginning of any block, and the switch statement requiring a block, or
at least to be useful;

In general it's not fair to look for extreme sense in C, it was just
supposed to be a pragmatic, ad-hoc language for use by some genius
coders at Bell Labs, 30+ years ago, for hecks sake!

Sep 20 '06 #4
i am using gcc available with Cygwin

Tejas Kokje wrote:
sunny wrote:
Hi

Why does C allows declaration of variable inside switch block.
ex: foll prg does not gives "undeclared "b" error msg. but also does
not initialize b to 20
int a=1;
switch(a)
{
int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf( "b is %d\n",b);
break;
}

this prints some garbage.
( yeah even though i got warning msg "unreachabl e code int b = 20" why
is it declaring inside switch block but not initializing b)


It depends on your compiler. I am using gcc and it throws following
warning message

[kokje@RocketFue l ~]$ gcc test.c -o test
test.c: In function `main':
test.c:7: warning: unreachable code at beginning of switch statement

What compiler are you using ?

Tejas Kokje
Sep 20 '06 #5

sunny wrote:
Hi

Why does C allows declaration of variable inside switch block.
because it allows declaration of variables inside any braced block.
ex: foll prg does not gives "undeclared "b" error msg. but also does
not initialize b to 20
int a=1;
switch(a)
{
int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf( "b is %d\n",b);
break;
}

this prints some garbage.
( yeah even though i got warning msg "unreachabl e code int b = 20" why
is it declaring inside switch block but not initializing b)
automatic variables (of which b is an example) are initialized as if by
an assignment (I'm talking casually here).

So it's as if the block starts with :-
{
int b; /* declaration */
b = 20; /* initialization */
case 1: <etc>

But in a switch statement only the operations following "case" or
"default" are executed. Hence the variable b is declared, but not
initialized.

Sep 20 '06 #6
Chris McDonald wrote:
You will probably be horrified by Duff's Device:
I'm not so much horrified as puzzled by the location of the while.
Is it the equivalent of a goto into a do loop?
Sep 20 '06 #7

sunny wrote:
Hi

Why does C allows declaration of variable inside switch block.
I went back to my dog-eared copy of K & R (1st edition).

On P.203 it says "Declaratio ns may appear at the head of [the subject
of a switch], but initializations of automatic and register variables
are ineffective".

So one answer to "why?" is "because that's what K & R said".

Sep 20 '06 #8
On 2006-09-20, sunny <su*******@gmai l.comwrote:
Hi

Why does C allows declaration of variable inside switch block.
ex: foll prg does not gives "undeclared "b" error msg. but also does
not initialize b to 20
int a=1;
switch(a)
{
int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf( "b is %d\n",b);
break;
}

this prints some garbage.
( yeah even though i got warning msg "unreachabl e code int b = 20" why
is it declaring inside switch block but not initializing b)
As the warning message stated, the initialization is unreachable code.
According to the specification:

Storage is guaranteed to be reserved for a new instance of such an
object on each normal entry into the block with which it is associated,
or on a jump from outside the block to a labeled statement in the
block or in an enclosed block. If any initialization is specified for
the value stored in the object, it is performed on each normal entry,
but not if the block is entered by a jump to a labeled statement.

The compiler is conforming to the specification, and it is giving a
warning about the initialization not being performed.
Sep 20 '06 #9
lovecreatesbea. ..@gmail.com posted:
ma**********@po box.com wrote:
>sunny wrote:
Hi

Why does C allows declaration of variable inside switch block.

because it allows declaration of variables inside any braced block.

Old C doesn't allow variables to be declared everywhere, right?

No, all declarations must appear at the beginning of a block, before any
expression statements.

What's the difference between a declaration and a statement?

A declaration declares something. Here are some examples of declarations:

int i;
typedef unsigned UInt;
int Func();

(the first one is a definition as well as a declaration.)

--

Frederick Gotham
Sep 20 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3207
by: Roy Yao | last post by:
Why the following code let my compiler complain an overloaded function Init()? // code begin template<class T> class BicircularList { template<class T> class Iterator; template<class T> class ChainNode { friend Iterator<T>;
70
8919
by: Roy Yao | last post by:
Does it mean "(sizeof(int))* (p)" or "sizeof( (int)(*p) )" ? According to my analysis, operator sizeof, (type) and * have the same precedence, and they combine from right to left. Then this expression should equal to "sizeof( (int)(*p) )", but the compiler does NOT think so. Why? Can anyone help me? Thanks. Best regards. Roy
71
4239
by: Christopher Benson-Manica | last post by:
At what point was the .h dropped from the STL headers? I just had a discussion yesterday with my boss, who said he wanted .h on all the STL includes, despite me protesting that it was not standard... -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
6
2852
by: Markus Dehmann | last post by:
I have a circular dependency between two classes. The FAQ hint about a forward declaration does not help in my case ( How can I create two classes that both know about each other?) Error: "field `foo' has incomplete type" for the following code: #include <iostream> #include <vector>
11
2453
by: aleko | last post by:
This applies equally to function prototypes. Why do we have to tell the compiler twice? Other modern compiled languages don't have this requirement. Just curious, Aleko
15
2055
by: Generic Usenet Account | last post by:
While I have a very good feel for how inlining works, I fail to see how in the world inlining can work if the inlined function is not described "in place" in a header file, but rather defined in a separate source file (using the inline keyword), which gets linked in? Does inling work at all in such cases? If it does, can someone kindly explain how the compilers handle that? If it does not, is that documented somewhere? Thanks, Gus
15
6735
by: Greenhorn | last post by:
Hi, when a function doesn't specify a return type ,value what value is returned. In the below programme, the function sample()is returning the value passed to 'k'. sample(int); main() { int i = 0,j; j = sample(0);
130
6648
by: Daniel Manes | last post by:
I'm baffled. I have a column in a SQL Server Express database called "Longitude," which is a float. When I view the table in a DataGridView, some of the numbers, which only have two decimal places in the database show up with *15* decimal places and are ever so slightly off (in the example in the subject line, by about 2E-15). I'm not doing any operations on this column. It's just running a stored procedure which performs a pretty basic...
13
1449
by: Paul Melis | last post by:
Can someone explain to me why the following code compiles without errors on gcc 4.0.2? void f() { } void t() { f(1,2,3);
0
9715
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10603
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10353
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9176
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4314
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3836
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.