473,839 Members | 1,532 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
15 54672
Richard Tobin schrieb:
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).
Have a look at C90, 6.1.2.1, or C99, 6.2.1.
From the latter (#3 and part of #4):
,---
3 A label name is the only kind of identifier that has function scope.
It can be used (in a goto statement) anywhere in the function in which
it appears, and is declared implicitly by its syntactic appearance
(followed by a : and a statement).
4 Every other identifier has scope determined by the placement of its
declaration (in a declarator or type specifier). If the declarator or
type specifier that declares the identifier appears outside of any block
or list of parameters, the identifier has file scope, which terminates
at the end of the translation unit. 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.e. you cannot think of function parameters as
foo()
{
/* Out-of-function: parameters and similar */
int bar;
{
/* start of function body */

}
/* take up the value given by return */
int retval = __return;
}
in "pseudo C" but really have to think of it as
foo()
{
/* Out-of-function */
{
/* parameter list */
int bar;
/* start of function body */

}
/* take up the value given by return */
int retval = __return;
}

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Aug 22 '06 #11
Herbert Rosenau <os****@pc-rosenau.dewrote :
>
Because it is NOT an error to override the name of a parameter.
In the outermost block of the function it is. 6.9.1p9 says that
parameters have block scope, so you have two declarations of the same
identifier with no linkage in the same scope, which violates the
constraint in 6.7p3.

-Larry Jones

These child psychology books we bought were such a waste of money.
-- Calvin's Mom
Aug 22 '06 #12
ri*****@cogsci. ed.ac.uk (Richard Tobin) writes:
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).
Here's the wording from C99:

6.2.1p4:
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.

6.2.1p6:
Two identifiers have the _same scope_ if and only if their scopes
terminate at the same point.

6.7p3 (this is a constraint):
If an identifier has no linkage, there shall be no more than one
declaration of the identifier (in a declarator or type specifier)
with the same scope and in the same name space, except for tags as
specified in 6.7.2.3.

Now consider the code in question:

void fun(int val)
{
int val;
/* ... */
}

The parameter val and the variable val both have block scope. The
"associated block" in both cases is the one defined by the opening and
closing braces. The scope of both "val"s terminates at the same
point, the closing brace. Therefore they're in the "same scope" as
defined in 6.2.1p6, and second declaration of val is a constraint
violation,requi ring a diagnostic (which can be either a warning, an
error message, or a smoke signal).

If there's an argument, based on the standard, that the two "val"s
*don't* have the same scope, I'd be interested in seeing it.

I don't believe I've ever seen any existing code that does this
deliberately rather than accidentally. If you really did want to hide
the parameter declaration for some reason, you could always create a
new block:

void fun(int val)
{
{
int val;
/* ... */
}
}

Here the scope of the parameter terminates at the outer '}', and the
scope of the variable terminates at the inner '}'.

Note that this would have been an easy mistake to make in pre-ANSI C,
without prototypes. Someone meaning to write this:

fun(val)
int val;
{
/* ... */
}

could accidentally write this:

fun(val)
{
int val;
/* ... */
}

If the compiler didn't complain, it would be a difficult error to
track down.

--
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 #13
In article <4l************ @individual.net >,
Michael Mair <Mi**********@i nvalid.invalidw rote:
>Have a look at C90, 6.1.2.1, or C99, 6.2.1.
From the latter (#3 and part of #4):
>3 A label name is the only kind of identifier that has function scope.
It can be used (in a goto statement) anywhere in the function in which
it appears, and is declared implicitly by its syntactic appearance
(followed by a : and a statement).
Could someone remind me whether the seperate namespace for
labels allows one to use label names that are the same as
library function names (or are reserved for future library
directions) ?

If duplication at that level is allowed, then we might have
a tie-in to the thread that is discussing whether strlen can
be a macro.
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Aug 22 '06 #14
[given code of the form:
void f(int var) { int var; /*...*/ }
]
>Chris Torek <no****@torek.n etwrites:
>The C standards require only a "diagnostic ". ...
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.orgw rote:
>Is even a diagnostic required in this case?
Yes. Others have quoted the appropriate C-standards sections (the
key is mostly that the two instances of "var" have the same scope
by virtue of having their scopes end at the closing brace). I think
it is worth adding, though, that historic (pre-C89) implementations
(or at least one such) did in fact have some "extra" scopes. In
those compilers (or "that compiler"?), the above was valid and
no diagnostic was required.

(The compiler I am most familiar with, in this case, is the old
VAX PCC. Scopes were numbered: level 0 was "file scope", level 1
was reserved for "function scope" -- goto labels -- and arguments,
and actual block-scope variables inside functions started at level
2. I remember this in particular because I worked on speeding up
the compiler: after a few of us did some other work on hot-spots,
profiling showed symbol table work as a high time-eater. This
turned out to be due to a linear scan of the entire symbol table
at every close brace:

for (all entries in the table) {
if (entry->level current_level)
remove this entry;
}

I put the entries into chains according to their levels, and the
time taken in the "remove entries from symbol table" code dropped
from about 15% to about 0.2%, if I remember right. Initially, I
had a bug in it, because I originally thought the "current level"
only ever went up or down one step at a time, but at the final
close brace for a function, it went from 2 to 0. The breakage was
"interestin g".)
--
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 23 '06 #15
Walter Roberson schrieb:
In article <4l************ @individual.net >,
Michael Mair <Mi**********@i nvalid.invalidw rote:
>>Have a look at C90, 6.1.2.1, or C99, 6.2.1.
From the latter (#3 and part of #4):
>>3 A label name is the only kind of identifier that has function scope.
It can be used (in a goto statement) anywhere in the function in which
it appears, and is declared implicitly by its syntactic appearance
(followed by a : and a statement).

Could someone remind me whether the seperate namespace for
labels allows one to use label names that are the same as
library function names (or are reserved for future library
directions) ?
I see nothing prohibiting it -- reservations are mostly for file
scope identifiers.
If duplication at that level is allowed, then we might have
a tie-in to the thread that is discussing whether strlen can
be a macro.
I follow said thread and think that having strlen being a macro
via
#define strlen __builtin_strle n
would have negative repercussions on
#define concat(a,b) a##b
#define JOIN(a,b) concat(a,b)
.....
JOIN(my, strlen)
whereas
#define strlen(s) __builtin_strle n(s)
has problems with
(strlen)(s)

Just consider the preprocessor output -- if your implementation
offers it -- of

#include <stddef.h>
#define concat(a,b) a##b
#define JOIN(a,b) concat(a,b)

#define strlen __builtin_strle n
size_t JOIN(my, strlen)(const char *);
#undef strlen
#define strlen(s) __builtin_strle n(s)

int main (void)
{
(strlen)(s);
return 0;
}
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Aug 23 '06 #16

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

Similar topics

3
9484
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
3231
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
2342
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
3045
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
7143
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
3499
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
4411
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
9696
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
10903
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
7827
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7015
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
5681
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4482
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
4063
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3131
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.