473,802 Members | 1,937 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

default const

Anyone know why "const" isn't the default for function parameters? I almost
never see code where function parameters are modified intentionally (and when I
do, I usually think copying the value to a local variable would be clearer), but
I do occasionally see function parameters being incremented instead of
similair-sounding local variables or, in the case of pointers, instead of the
objects they point to.

e.g.:

void foo(int *x, int link)
{
int lnk = 0;
x++; /* Meant to increment *x */
link++; /* Meant to increment lnk */
....
}

I'm not trying to convince anyone to change the language, just curious about how
it ended up this way.

<OT> Has anyone come across a compiler or other tool that can report warnings
for non-const parameters being modified? </OT>

Ed.

Nov 13 '05 #1
3 2040
Ed Morton wrote:

Anyone know why "const" isn't the default for function parameters?
Only an actual member of the committee that wrote the ANSI
standard could answer authoritatively . However, the semantics
of function parameters had been part of C for twenty-odd years
before the ANSI standard brought `const' into the language.
Applying an implicit `const' to function parameters would have
changed those semantics, and would have broken some amount of
code that relied on the old semantics. (And might have led to
a `nonconst' keyword to override the default.)

Now, the committee did introduce new keywords to the language,
and the committee did occasionally introduce semantic changes,
sometimes quiet ones. My speculation is that this particular
change (if it was ever considered at all) probably didn't meet
the committee's "minimal outrage" standard.
I almost
never see code where function parameters are modified intentionally (and when I
do, I usually think copying the value to a local variable would be clearer), but
I do occasionally see function parameters being incremented instead of
similair-sounding local variables or, in the case of pointers, instead of the
objects they point to.

e.g.:

void foo(int *x, int link)
{
int lnk = 0;
x++; /* Meant to increment *x */
link++; /* Meant to increment lnk */
....
}
Programmers are free to choose confusing or misleading
identifiers; the language standard doesn't legistlate style
or good sense.

Also, wouldn't your suggestion of copying `const' parameters
to local variables simply make this kind of confusion more likely?
For example (pardon the syntax):

void foo(int * implicitconst x, int implicitconst link) {
int * nonconst X = x;
while (*X != 0) ++X;
*x = link; /* meant to store to *X */
}

That is, a requirement to copy the parameters would very likely
lead to a profusion of similar-looking names, which in turn might
make it more probable that the programmer accidentally grabs the
wrong member of an associated pair.
I'm not trying to convince anyone to change the language, just
curious about how it ended up this way.


Non-authoritative, but highly suggestive:

"Call by value is an asset, however, not a liability. It
usually leads to more compact programs with fewer extraneous
variables, because arguments can be treated as conveniently
initialized local variables in the called routine."

-- B.W. Kernighan and D.M. Ritchie, "The C Programming
Language" (first edition), section 1.8

--
Er*********@sun .com
Nov 13 '05 #2
"Ed Morton" <mo************ ****@Lucent.com > wrote in message
news:3F******** ******@Lucent.c om...
Anyone know why "const" isn't the default for function parameters?
I don't *know* why, but I don't see any need.
"Why" can only be answered by Mr. Ritchie and/or
ISO C standard committee members.
I almost
never see code where function parameters are modified intentionally
Yes, its very common that functions do not modify their
parameters. But it is done. I do it on occasion myself.
(and when I
do, I usually think copying the value to a local variable would be clearer),

Note that a function parameter *is* essentially a 'local variable'.
but
I do occasionally see function parameters being incremented
Yes, I do this sometimes. Why create another object when
you don't need to?

int digits(int value)
{
/* no need for a copy of 'value' */
int count = 0;
while(value)
{
++count;
value /= 10; /* modify 'value' */
}

return count;
}
void foo()
{
int i = 42;
int d = digits(i); /* 'i' is not changed */
}
instead of
similair-sounding local variables or, in the case of pointers, instead of the objects they point to.
Modifying the value of a pointer vs its 'target' are
two distinct operations. Which one is done depends
upon the purpose of the function.

e.g.:

void foo(int *x, int link)
{
int lnk = 0;
x++; /* Meant to increment *x */
Then that's simply a coding mistake.
The pointer is incremented, not its target.

But note that many functions with pointer parameters
are indeed written with a 'const' qualifier for
either the pointer or its target (e.g. strcpy(),
strcmp(), etc.)

link++; /* Meant to increment lnk */
Another coding error. But there's nothing wrong with
modifying 'link' (unless of course later code depends
upon the originally passed value.) This is a factor
in my decision whether I'll modify the parameter itself
or first make a copy in a local object. IOW, *think*
about what the function will do before/during writing it.
:-)
....
}

I'm not trying to convince anyone to change the language, just curious about how it ended up this way.
Perhaps the folks over at comp.std.c can give you the
history and rationale about this. That group is about
things like this, this group is for using the language
the way it is.

<OT> Has anyone come across a compiler or other tool that can report warnings for non-const parameters being modified? </OT>


Why should a compiler warn about modifying a nonconst object?
Feel free to define your parameters as const if you feel it
will help you write better code.

-Mike
Nov 13 '05 #3
In 'comp.lang.c', "Mike Wahler" <mk******@mkwah ler.net> wrote:
Feel free to define your parameters as const if you feel it
will help you write better code.


I have done that for 6 years now, and yes, I like it, and it makes my code
more solid. I like to say:

"Modifying a parameter is often the sign of a bad design."

or

"The value received as a parameter is as precious as gold. Don't waste it."

--
-ed- em**********@no os.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 13 '05 #4

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

Similar topics

2
3078
by: Gary | last post by:
Hi, I am a Chinese student, I have a problem with the following code //The follwing code in StaticSearch.h: // template <class Type> class dataList; // template <class Type> class Node //Êý¾Ý±íÖнáµãÀàµÄ¶¨Òå
11
1585
by: puzzlecracker | last post by:
not sure of the stardard: which one is right, if both which one is preferable? class FOO{ void foo(const string &, const string &username="true"); ..... } void FOO::foo(const string & cycle, const string &username="true")
4
1727
by: BigMan | last post by:
Why does an emtpy class require an explicit default ctor in order to initialize const objects of that type: class EmptyClass { }; class EmptyClass2 { EmtpyClass2( ) { }
16
2582
by: Steven T. Hatton | last post by:
As far as I know, there is no way to provide a default value for the argument to the constructor A::A(char (&array)) in this example. Correct? struct A{ A(char (&array) ){ std::copy(&array,&array,&_array); } char _array; };
7
2574
by: shikn | last post by:
I wrote one simple piece of codes to test const objects in C++ as below: ================================= class Empty{}; main() { const Empty e1; } ==================================
1
2613
by: Wayne | last post by:
I'm using the following code from the Access Web to open a folder. The folder opens in "List" View. Is there an addition that I can make to the code to force the folder to open in "Details" view? 'This code was originally written by Ken Getz. 'It is not to be altered or distributed, 'except as part of an application. 'You are free to use it in any application, 'provided the copyright notice is left unchanged. '
4
7242
by: sods | last post by:
Hi, I write a test code about template used for strategy. it's very similar to sample code in TC++PL 13.4.1. #include <iostream> #include <string> using std::basic_string;
11
2354
by: Matthias Pfeifer | last post by:
Hi there, I am trying to declare a function that takes a std::list<parameter. I want this function to have an empty list as a default parameter. It's a template function also. Currently i am stuck because my compiler does not find a matching function when i do a call. here is my code: // ############## code begins
43
3841
by: JohnQ | last post by:
Are a default constructor, destructor, copy constructor and assignment operator generated by the compiler for a struct if they are not explicitely defined? I think the answer is yes, because "there is no difference between a struct and a class except the public/private access specification" (and a few minor other things). When I create a class, I always start by declaring the default constructor, copy constructor and assignment operator...
9
2905
by: puzzlecracker | last post by:
From my understanding, if you declare any sort of constructors, (excluding copy ctor), the default will not be included by default. Is this correct? class Foo{ public: Foo(int); // no Foo() is included, i believe. };
0
9699
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
9562
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
10305
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...
0
10063
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
9115
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
6838
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
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
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
3
2966
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.