473,889 Members | 1,927 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

declaration shadows a parameter

Hi all,

When i compile following piece of code,

# include <stdio.h>

void fun(int val)
{
int val; /*problem is here*/
printf("%d\n",v al);
}

int main()
{
int num = 1;
fun(num);
return 0;
}

Compiler gives a warning (why not an error?),
In function `fun':
warning: declaration of `val' shadows a parameter

But what i expected is an error something like this,
error: redeclaration of `val'

Can someone explain me the warning ?
Thanks for your time.
Yugi

Don't say to GOD how big your problem is
Say to your problem how big your GOD is

Aug 22 '06 #1
15 54696
main() wrote:
Hi all,

When i compile following piece of code,

# include <stdio.h>

void fun(int val)
{
int val; /*problem is here*/
printf("%d\n",v al);
}

int main()
{
int num = 1;
fun(num);
return 0;
}

Compiler gives a warning (why not an error?),
In function `fun':
warning: declaration of `val' shadows a parameter

But what i expected is an error something like this,
error: redeclaration of `val'

Can someone explain me the warning ?
For ease of reference I will call val-A the parameter passed
to the function fun() and val-B the variable declared inside
fun().

What the warning means is that while val-B is in scope ,
every time you use val you will get the value stored inside
val-B not the value passed in val-A. Here's an example:

#include <stdio.h>
int main(void) {
int i=1 ;

printf("%d\n",i ) ;
{
int i=2 ;
printf("%d\n",i ) ;
}
printf("%d\n",i ) ;
return 0 ;
}

The above code will produce output
1
2
1

Shadowing a variable by another variable with the same
name can be useful in certain circumstances although
some would consider it poor style. Consider the following
example.

#define macrofoo(a) { \
int i ; \
/* Code which uses among other things i \
* as an index variable */ \
}

int foo(void) {
int i,a ;
/* More code
......
*/
for (i=1;i<10;i++)
macrofoo(a)
}

In the above example the variable i defined
inside macrofoo takes values independently
from the variable i defined inside foo(). If you
are really passionate about using the name i
for index variables and you want to use macrofoo
in more than one places then you might write
such code. For that reason , when shadowing
occurs you'd want to have a warning rather than
an error which would make the code uncompilable.

Finally , I note that the concept of shadowing appears
in other programming languages.

Spiros Bousbouras

Aug 22 '06 #2
In article <11************ **********@b28g 2000cwb.googleg roups.com>
main() <dn****@gmail.c omwrote:
void fun(int val)
{
int val; /*problem is here*/
[snippage]
Compiler gives a warning (why not an error?) ...
The C standards require only a "diagnostic ". A warning, an error,
a beep, flashing the screen, or squirting water out of the floppy
drive (if you still have a floppy drive) can all be a "diagnostic ".
(The documentation that comes with the compiler should say something
about its diagnostics.)

See also <http://web.torek.net/torek/c/compiler.html>.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Aug 22 '06 #3
main() wrote:
When i compile following piece of code,
# include <stdio.h>

void fun(int val)
{
int val; /*problem is here*/
printf("%d\n",v al);
}
Compiler gives a warning (why not an error?),
gcc errors on this:

b.c:8: error: 'val' redeclared as different kind of symbol

--
Bill Pursell

Aug 22 '06 #4
Chris Torek <no****@torek.n etwrites:
In article <11************ **********@b28g 2000cwb.googleg roups.com>
main() <dn****@gmail.c omwrote:
>void fun(int val)
{
int val; /*problem is here*/
[snippage]
>Compiler gives a warning (why not an error?) ...

The C standards require only a "diagnostic ". A warning, an error,
a beep, flashing the screen, or squirting water out of the floppy
drive (if you still have a floppy drive) can all be a "diagnostic ".
(The documentation that comes with the compiler should say something
about its diagnostics.)
Is even a diagnostic required in this case?

C99 6.2.1p4 says:

If the declarator or type specifier that declares the identifier
appears inside a block or within the list of parameter
declarations in a function definition, the identifier has block
scope, which terminates at the end of the associated block.

I think this means that the scope of the parameter is the outer block
of the function, even though it's declared before the opening '{'.

--
Keith Thompson (The_Other_Keit h) ks***@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.
Aug 22 '06 #5
On Tue, 22 Aug 2006 04:31:27 UTC, "main()" <dn****@gmail.c omwrote:
Hi all,

When i compile following piece of code,

# include <stdio.h>

void fun(int val)
{
int val; /*problem is here*/
printf("%d\n",v al);
}

int main()
{
int num = 1;
fun(num);
return 0;
}

Compiler gives a warning (why not an error?),
In function `fun':
warning: declaration of `val' shadows a parameter

But what i expected is an error something like this,
error: redeclaration of `val'

Can someone explain me the warning ?
Because it is NOT an error to override the name of a parameter. It may
be a mistake to do so, but the only who knows that it is a mistake is
the one who wrote the code.

As it is legal to override the name the compiler may or may not warn
you here.

Anyway you should initialise each auto variable with 0 or an value
that flags the variable as faulty. That will help you to dedect the
mistake that you have not set it right later on.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Aug 22 '06 #6
"Herbert Rosenau" <os****@pc-rosenau.dewrite s:
On Tue, 22 Aug 2006 04:31:27 UTC, "main()" <dn****@gmail.c omwrote:
> When i compile following piece of code,

# include <stdio.h>

void fun(int val)
{
int val; /*problem is here*/
printf("%d\n",v al);
}

int main()
{
int num = 1;
fun(num);
return 0;
}

Compiler gives a warning (why not an error?),
In function `fun':
warning: declaration of `val' shadows a parameter

But what i expected is an error something like this,
error: redeclaration of `val'

Can someone explain me the warning ?

Because it is NOT an error to override the name of a parameter. It may
be a mistake to do so, but the only who knows that it is a mistake is
the one who wrote the code.

As it is legal to override the name the compiler may or may not warn
you here.
I don't believe that's correct. Both the parameter and the local
object are at the same block scope, even though the parameter is
declared before the opening '{' of the scope. See C99 6.2.1.

But as far as programmers are concerned, it doesn't matter much
whether it's legal or not; just don't do it, and be glad that the
compiler at least warned you about it.

--
Keith Thompson (The_Other_Keit h) ks***@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.
Aug 22 '06 #7
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.orgw rote:
>Because it is NOT an error to override the name of a parameter. It may
be a mistake to do so, but the only who knows that it is a mistake is
the one who wrote the code.

As it is legal to override the name the compiler may or may not warn
you here.
>I don't believe that's correct. Both the parameter and the local
object are at the same block scope, even though the parameter is
declared before the opening '{' of the scope. See C99 6.2.1.
That seems very surprising. It would have broken existing code to
prohibit it in the standard, and as far as I can remember I have never
used a compiler that treated it as an error (rather than a warning).

-- Richard
Aug 22 '06 #8

main() wrote:
Hi all,

When i compile following piece of code,

# include <stdio.h>

void fun(int val)
{
int val; /*problem is here*/
printf("%d\n",v al);
}

int main()
{
int num = 1;
fun(num);
return 0;
}
C has always been a bit fuzzy about parameter declarations. In the
original K&R C, the suggestion was to just mention the parameter names
in the parentheses, then associate the names with types after the
header but before the function block (somewhat like FORTRAN).

The new standard is to mention both the type and name in the header.
Which leaves open the question whether the header has its own lexical
nesting level, or is at the same level as the function body.

If the header is its own level, then it's okay to declare another
variable (or const, or type) inside the function body.

If the header is at the same level as the function body, then it should
be an error to redeclare the same name.

It appears your compiler thinks the header has its own nesting level,
but also warns you if you write this somewhat problematical
declaration.


>
Compiler gives a warning (why not an error?),
In function `fun':
warning: declaration of `val' shadows a parameter

But what i expected is an error something like this,
error: redeclaration of `val'

Can someone explain me the warning ?
Thanks for your time.
Yugi

Don't say to GOD how big your problem is
Say to your problem how big your GOD is
Aug 22 '06 #9
On 22 Aug 2006 19:07:44 GMT, ri*****@cogsci. ed.ac.uk (Richard Tobin)
wrote:
>In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.orgw rote:
>>Because it is NOT an error to override the name of a parameter. It may
be a mistake to do so, but the only who knows that it is a mistake is
the one who wrote the code.

As it is legal to override the name the compiler may or may not warn
you here.
>>I don't believe that's correct. Both the parameter and the local
object are at the same block scope, even though the parameter is
declared before the opening '{' of the scope. See C99 6.2.1.

That seems very surprising. It would have broken existing code to
prohibit it in the standard,
I find that surprising. I think I've seen that done only twice in
several million lines of code, and both times were errors.
>and as far as I can remember I have never
used a compiler that treated it as an error (rather than a warning).
Bill Pursell posted one yesterday.

--
Al Balmer
Sun City, AZ
Aug 22 '06 #10

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

Similar topics

3
9485
by: Aguilar, James | last post by:
Hey all. I was making a newbie mistake that I eventually figured out. That is not my question. My question is about the error message. So let me set the stage for you: class Superclass { public: Superclass(int); }
10
3235
by: Özden Irmak | last post by:
Hi, I'm trying to hide an event of my custom usercontrol derived control, something like "Shadows" in VB.Net, but although the event is hidden from PropertyGrid, from CodeEditor I can still see/reach it. I use this code :
4
2343
by: Brian Lowe | last post by:
I have several aspx pages that include a couple of asp:placeholder controls, an example is myPage.aspx. The page inherits from a custom class 'myClass' which inherits System.Web.UI.Page which lets me ad my own properties and methods to a bunch of pages in my app. I want code in myClass to set the contents of the placeholders in myPage. If I insert the mark-up <asp:placeholder id="myPlaceholder" runat="server"
10
3048
by: Lino Barreca | last post by:
Take a look at this code: Class clsAnagrafica Public Overridable ReadOnly Property Codice() As Integer Get Return 1 End Get End Property End Class
7
7144
by: Satish | last post by:
Hi Friends I am little confused about the shadows keyword in VB.NET could anyone explain with an example about Shadows keyword Many thanks Satish
3
2009
by: flat_ross | last post by:
For anyone who is just getting into VB.NET and/or is starting to work with inheritance I would like to point out a potential pitfall. We found this confusion recently when code-reviewing an application. If you have not used the keyword 'Overridable' then read on for sure... If you setup a child class and you want to override a method in your base class, you may see the squiggles under your child's method name. The pop-up/build error says...
6
3502
by: Robbie Hatley | last post by:
I just ran across this code at work: BOOL main_AddDefaultBenchHeaterPeriods // ??? ( DWORD main_AddDefaultBenchHeaterPeriods // ??? ) { // ... two dozen lines of code ...
11
4414
by: wuzertheloser | last post by:
Write a program which calculates the integral of the function f(x)=(A*x^m)/n! on the interval from a to b (0<a<b). In the main program, scanf a double value for m and a non-negative integer value for n, a double value of A, and positive double values for a and b>a. Call the function Intgr() to evaluate the integral. Your main program should be followed by three functions:
0
9969
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
9810
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11203
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...
1
10896
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
10443
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9612
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
7151
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();...
2
4251
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3257
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.