Re: Re-use the argument?
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sat, 07 Jun 2008 01:46:06 -0700
Tomás Ó hÉilidhe <toe@xxxxxxxxxxx> writes:
On Jun 7, 8:26 am, Richard Heathfield <r...@xxxxxxxxxxxxxxx> wrote:
But if your question is: is it worth const-decorating parameters for the
hell of it?, the answer is "no". C is a pass-by-value language.
I was refering purely to the "re-using" of the function argument. A
person might think that the latter version would result in more
efficient code because it does not use a temporary variable for doing
the calculations, but then again this benefit could be rescinded by i)
the use of an acumulator register or ii) the compiler's automatic re-
using of const variables when it knows they're no longer needed. Or
then again the person might just choose the former without any
consideration, leaving it all in the hands of the compiler.
I'm just more curious as to what I'd get for a "Yes or No" answer to
this from people. Would you do a simple R-value expression:
return 3*x - 2;
or would you attempt to do individual operations on the argument:
x *= 3;
x -= 2;
return x;
You chose a poor example. There's no advantage in breaking down such
a trivial calculation into three separate statements. This really has
nothing to do with whether modifying a parameter object is a good
idea; it's just a matter of writing clear code.
What you *meant* to ask, I think, is whether it's a good idea to use a
function parameter as an ordinary modifiable object. And the answer
is, it depends. If it makes the code clearer, go ahead. If it
doesn't, don't.
There is something to be said for leaving a parameter with the
original value that was passed in, so the name means the same thing
throughout the function. But it's not a hard and fast rule.
Declaring a parameter as "const" is a bit tricky, since it's
meaningful only inside the function, even though it's visible to
anyone who looks at the function declaration. (I'm not sure whether
you can legally use "const" on a parameter in the definition, but not
in a separate declaration.)
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- Follow-Ups:
- Re: Re-use the argument?
- From: Ben Bacarisse
- Re: Re-use the argument?
- References:
- Re-use the argument?
- From: Tomás Ó hÉilidhe
- Re: Re-use the argument?
- From: Richard Heathfield
- Re: Re-use the argument?
- From: Tomás Ó hÉilidhe
- Re-use the argument?
- Prev by Date: Re: A CT&P excursion - beat it up!
- Next by Date: Re: A CT&P excursion - beat it up!
- Previous by thread: Re: Re-use the argument?
- Next by thread: Re: Re-use the argument?
- Index(es):
Relevant Pages
|
Loading