Nested conditional expressions ---- good idea/bad idea?


    Sponsored Links


  • 1. lower number
    i, If i have an array like {1,4, 10, 15 , 20 , 30 } of size n , now if i want to search for number 25 , i should get 20 , if i search for number 11 i hould get 10 , if i search for 4 i should get 4, if i search for a number and it doesn't exist i should get the lower number between which it lies. All numbers are bound to lie between 1 and n. Can you tell me a easy way to do it.
  • 2. Writing a custom libc
    where can I get the pieces needed to write a custom C library? I ask because I'm working on a rather large set of libraries where the extra stuff in glibc is a waste of space.
  • 3. -Bstatic flag
    Hi all, Can some body explain why -Bstatic flag is used on Solaris. I think this flag is not supported in sunstudio 11 compiler. when I pass compilation row, cc -Bstatic x.c I got the following error, d: fatal: library -lc: not found ld: fatal: File processing errors. No output written to a.out thanks in advance, Seema Rao

Nested conditional expressions ---- good idea/bad idea?

Postby nimmi_srivastav » Mon, 31 Jan 2005 10:12:49 GMT

Below you will see an example of a nested conditional expression that
this colleague of mine loves.  He claims that it is more efficient that
a multi-level if-else-if structure.  Moreover, our complexity analyzer
tool supposedly does not pick it up.  Is it really more efficient?
Personally I find this coding style extremely cryptic, misleading and

I believe that I have removed all traces of proprietary-ness from this
coding example by multiple text substitutions.


#include <stdio.h>

#define QWER 0x1000
#define TYUI 0x2000
#define ASDF 0x4000
#define GHJK 0x8000
#define ZXCV 0x10000
#define BNML 0x20000

print_value(int code, int type)
printf(" ==>  %s, Type %02X \n",
(code == QWER      ? "QWER":
code == TYUI      ? "TYUI":
code == ASDF      ? "ASDF":
code == GHJK      ? "GHJK":
code == ZXCV      ? "ZXCV":
code == BNML      ? "BNML": "????"),

print_value(BNML, 256);
print_value(ZXCV, 512);
print_value(GHJK, 1024);
print_value(ASDF, 768);
print_value(TYUI, 128);
print_value(QWER, 64);
  print_value(BNML|QWER, 32);

Re: Nested conditional expressions ---- good idea/bad idea?

Postby » Mon, 31 Jan 2005 11:49:05 GMT


The idea of efficiency is not a C language issue.

it is


Efficiency depends on things outside the scope of C (compiler,
processor, etc.).  I doubt there would be any meaningful efficiency
gain from doing this, it might even be more inefficient (confuses
compiler's optimization stages?!?).  I personally would never write
code like this, and I question the motives of programmers that do
(showing off? making their code harder for other to understand?).

[OT] If this is an embedded system with scarce resources, and you need
every nanosecond of time and bit of memory, then run tests (don't guess
by looking at C code- that is out of the question!!!!). Early on in the
software engineering process, your company probably did a thorough
study of possible "coarse" granular optimization practices that will
help make efficient code for your particular implementation.  Stick to
this, but don't play around with little details in the C source (keep
code looking clean). Near the end of your design cycle, if you find you
still need more optimization (which you shouldn't if you prepared
properly) then fine tune it (fine-granular optimizations). But
compilers these days are quite good at doing these optimizations for
you, so only "try" your tweaks if everything else fails (which it
shouldn't have, if you planned properly). Also, prepare for
optimizations by building proper interfaces (like making custome
interfaces for everything, including data types.. imagine that coding
is all done, but you realize that using int instead long for a whole
section of code will increase speed by a factor of 2 without breaking
the code... do you want to make a 1 line change or ... you get the

Re: Nested conditional expressions ---- good idea/bad idea?

Postby CBFalconer » Tue, 01 Feb 2005 00:09:36 GMT

... snip ...

After putting some decent indentation in (see sig below) you have:

The other choice here is a temporary, and an if else chain:

   char *tmp;

   if      (code == QWER) tmp = "QWER";
   else if (code == TYUI) tmp = "TYUI";
   else if (code == ASDF) tmp = "ASDF";
   else if (code == GHJK) tmp = "GHJK";
   else if (code == ZXCV) tmp = "ZXCV";
   else if (code == BNML) tmp = "BNML";
   else                   tmp = "????";
   printf(" ==> %s, Type %02X \n", tmp, type);

Now, which is cleaner and more readable?  Ignoring efficiency, I
think your colleague is doing just fine in this case.  There are
few places where I would use the ? operator, yet this is one of
them.  I would, however, probably isolate it in a routine such as:

     char *typetostring(enum type t);

which would allow

     printf(" ==> %s, Type %02X \n", typetostring(code), type);

You still have the temporary, it is just effected by the function
return value.  However you can reuse the translation routine if
needed elsewhere.

"If you want to post a followup via, don't use
 the broken "Reply" link at the bottom of the article.  Click on 
 "show options" at the top of the article, then click on the 
 "Reply" at the bottom of the article headers." - Keith Thompson

Re: Nested conditional expressions ---- good idea/bad idea?

Postby Luke Wu » Tue, 01 Feb 2005 03:22:31 GMT


I personally would never nest ternary : ? opeartors like this
(especially never putting the whole thing inside a printf argument!).
If statements are less error prone and in this case, there really is no
reason to use :? operators (count the difference in number of

Re: Nested conditional expressions ---- good idea/bad idea?

Postby Eric Sosman » Wed, 02 Feb 2005 00:20:32 GMT

    State your preference:

	hand_type = is_straight
	    ? is_flush ? STRAIGHT_FLUSH : STRAIGHT
	    : is_flush ? FLUSH : NOTHING;


	if (is_straight) {
	    if (is_flush) {
	        hand_type = STRAIGHT_FLUSH;
	    else {
	        hand_type = STRAIGHT;
	else {
	    if (is_flush) {
	        hand_type = FLUSH;
	    else {
	        hand_type = NOTHING;

Neither is "righter" or "wronger" than the other, and
both clarity and beauty lie in the eye of the beholder.
Still, to my eye the first is preferable.


Re: Nested conditional expressions ---- good idea/bad idea?

Postby Gregory Dean » Wed, 02 Feb 2005 00:28:36 GMT

On 1/31/05 10:20 AM, in article ctlic0$ffm$ XXXX@XXXXX.COM , "Eric

Debugging is much easier in the latter. Try to set a breakpoint on the
ternary version.

Re: Nested conditional expressions ---- good idea/bad idea?

Postby Eric Sosman » Wed, 02 Feb 2005 05:29:52 GMT

    (1) No problem, if you'll let me choose a de{*filter*}
that can set breakpoints at arbitrary machine instructions.

    (2) Try to set a breakpoint in the latter form, after
an optimizing compiler has transmogrified the code and
generated the same instructions as for the former form.

    (3) Debugging is inferior to inspection, in the sense
that a de{*filter*} can (at best) show you things that have
actually happened, while inspection can drive assertions
about all the things that can and cannot happen.  I feel
that the former is easier to inspect than the latter, hence
easier to prove things about, hence less likely have bugs
in the first place!

    (4) De{*filter*}s are like crutches: When you need them
you do in fact need them, but you will never progress as
well as when you can do without them.

    (5) -- no, I'm starting to rant.  Again ...


Re: Nested conditional expressions ---- good idea/bad idea?

Postby Big K » Fri, 04 Feb 2005 04:30:26 GMT

ric Sosman wrote:
ctlic0$ffm$ XXXX@XXXXX.COM , "Eric
is no

Yes, they are both "right," but the question is whether or not people
"accept" a method as being clear. In the real world, we don't keep our
code to ourselves (only in the fake world we do that), we share it and
allow others to understand it. I am pretty sure the people who find
the IF STATEMENTS "appropriate" are a superset of the ones that find
the nested CONDITIONALS "appropriate." In a software engineering
team, it's better to aim for the superset.

If you're only coding alongside seasoned veterans, without any junior
programmers, then the two sets are probably the same and you will have
no problem.

Do you have the luxury of choosing IDEs where you work? What if someone
else wrote the code and tested it for an IDE that doesn't offer the
features that you want? So your de{*filter*} has to conform to your code,
instead of your code being more universally debuggable? Source-level
debugging doesn't guarantee anything about machine instructions
You are assuming that the ternary form doesn't need optimizing and that
the IF form, when optimized, produces the same code as the ternary form
(and otherwize creates more machine instructions). In fact, a friend of
mine who is a compiler writer told me that compilers he has written
would optimize the IF's better than the deeply nested ternaries.

You can always turn optimization off to debug a section of code you
know will be heavily optimized.
You are comparing apples to organges. People don't pick debugging OVER
inspection or vice versa. The two happen at different phases and deal
with different problems. We should code to best satisfy all phases of
development/debugging, not one over the other.
IF statements are better for code inspections than DEEPLY NESTED
conditional ternaries. IF statements allow for braces to surround
different blocks that correspond to different conditions. Say if you
use extended bracing, you can draw lines from the top brace of every
block to the bottom brace of every block (in coloured pencils or
visually). This give so much more visibility than nested ternary

I like how you made the IF statements look overly expensive(with
brackets) while making the ternary statements look very clean in your
presentation above.

I see, so you're that famous programmer I read about in magazines that
never needed de{*filter*}s. That means you're a PERFECT software engineer
and a very LUCKY software engineer that only ran into code written by
other PERFECT software engineers.
I might be guilty of the same. I see no problem in the ternary
conditionals, but I work with a lot of beginner programmers (hardware
guys who are programming for the sake of controlling their hardware),
so for me the "superset" has far more members than the "subset."

Re: Nested conditional expressions ---- good idea/bad idea?

Postby Eric Sosman » Fri, 04 Feb 2005 06:09:24 GMT

Big K wrote:

If we eliminate from C all the things some people find
confusing, what will remain? The traffic in this newsgroup
shows that people are confused by arrays, by pointers, by
floating-point arithmetic, by much of <stdio.h> (printf()
makes lots of trouble, scanf() even more), by all of <ctype.h>,
by structs, by functions with prototypes, by functions without
prototypes, by variable-length argument lists, and by main().

Purging C of all these (and of the many other confusions
I haven't listed; these are off-the-top-of-my head topics)
would leave a language that might be named "C minus" but would
certainly not merit so high a mark ...

>>>Debugging is much easier in the latter. Try to set a breakpoint on

Are you arguing that de{*filter*}s should not have capabilities
not shared by all other de{*filter*}s? That is, that there should
be just one Ur-de{*filter*}?

No; I'm assuming that some compiler somewhere might generate
the same code for both forms.

Strange; the latter should be easier. For starters,
there's only one assignment target, hence no need to "notice"
that the four targets in the `if' form are in fact the same.

Perhaps your friend may have been referring to code like

#define max2(a,b) ((a) > (b) ? (a) : (b))
#define max4(a,b,c,d) max2(max2((a),(b)), \

... which I would most definitely not recommend; the apparent
simplicity conceals a surprisingly voluminous expansion, with
lots of common sub-expressions a compiler might need to struggle
to eliminate.

... at which point you are no longer debugging the actual code,
but a sort of proxy for it. I've debugged plenty of problems
that only showed up after optimization, that is, problems that
simply vanished when optimization was turned down or off. "Test
what you fly; fly what you test."

Different development activities have different goals and
are sometimes in conflict. It is not always possible to "best
satisfy" all of them; compromises are required.

However, I'll still maintain that it's better to be able
to prove things about a section of code than to run a bunch
of test cases through it and say "Well, nothing broke. Yet."

Proof by assertion. (You're in good company; Edsger W.
Dijkstra did a lot of important work, but is probably best
known for just such a proof.)

If you feel like it, you can do the same with ternaries:

= is_flush
? is_straight
: is_straight

... and you can even throw in a few levels of parentheses if
you want them.

Observation #1: Didn't you just get through saying
you *liked* all those braces?

Observation #2: Did you just describe the ternary
formulation as "very clean?" My point, exactly.

Excuse me, but what justifies this insult? Did I not say
that "When you need them you do in fact need them?" Yes, I
did. Did I claim perfection? No, I did not. Back off.

Clarity of expression is not achieved through baby talk.


Re: Nested conditional expressions ---- good idea/bad idea?

Postby john_bode » Fri, 04 Feb 2005 06:48:33 GMT


Make him show you the profiling data he gathered that allowed him to
reach this conclusion.

Terse code doesn't necessarily equate to fast or efficient code.  In
fact, I can think of cases the opposite is true; unrolling a loop
results in more verbosity, but can improve perfomance.  OTOH, a terse
recursive algorithm can incur significant overhead compared to a more
verbose, iterative equivalent (fibonacci or factorials, for example).

Having said that, it's possible that nested ternary expressions are
faster/smaller than an equivalent if-else structure, but you'd have to
profile the two versions to know for sure.

Re: Nested conditional expressions ---- good idea/bad idea?

Postby Big K » Fri, 04 Feb 2005 07:51:08 GMT

ric Sosman wrote:
We're talking about two different ways to do the same thing by an
actual developer (read original post), not about the mistakes made by
people learning the language. I guess the DEEP TERNARY NESTING vs.
MULTILEVEL IF is just a difference of opinion, let's leave it at that.
Once again, this is not a discussion about "purging" ternary operators
from the language and forcing developers to use IF statemetns. We're
talking about a solution to a problem (presented by the original
poster), that can be solved by NESTED TERNARIES or MULTILEVEL IF
statements. Nobody is talking about removing actual features from the
language. If you read the original post, you will see that the
individual was "at first glance" confused by the use of nested
ternaries. He also mentioned that certain tools his company used
couldn't recognize the nested ternaries, while it recognized the
multilevel IFs. I don't know where you go the idea that I wanted to
"purge" features from the language. Ternaries are awesome, but their
use in deep nesting can cause problems to less experienced developers,
optimizers, de{*filter*}s, complexity analyzers, etc (which was the subject
of the original post- have a look).

I am not bashing ternary operators or you're use of them. You probably
use it in a much clearer way than in the code the OP encountered,
which is fine.
No, but if you read the concerns of the OP, you will notice that his
tools had trouble recognizing the ternary conditionals AND he was
dealing with code developed by someone else. If you have a really
awesome de{*filter*} that lets you set machine level breakpoints while
stepping through source level code, then I guess this is a non-issue.
Then what did you mean by this comment:
(2) Try to set a breakpoint in the latter form [with IFs], after
an optimizing compiler has transmogrified the code and
generated the same instructions as for the former form.
If you meant that a compiler somewhere might generate the same code for
both forms, then how does your comment above (2) support nested
[Not insulting, I am just confused]

Different of opinion among different people. Let's leave it there.
Nope, wasn't referring to that.
I was responding to your comment (2). A compiler is free to optimize
either form, so I had no clue what your comment (2) was trying to
convey. Of course you should turn optimization on again after you have
found the fault with the de{*filter*} (that's if you had to resort to
turning it off in the first place, which is always a last-hope method).
NASA's mantra "test what you fly; fly waht you test" is posted above
the whiteboard beside me. But what is wrong with doing intermediate
tests on proxies to find a fault, then doing thorough tests on the real
thing afterwards?

Code inspections don't catch all bugs, neither does debugging. There is
no "better" method. You try to catch bugs as early as possible, and
you make every phase in the development cycle as robust as possible-
you can't make compromises. Everything must be taken seriously, there
are no preferences.

Difference of opinion. But realize that you can't rely solely on code

Proof? It's an opinion that was a response to your opinion.
Difference of opinion.
I like extended braces (read my comment

Similar Threads: good/bad ?


in my personal tcl/sqlite  table structure changer, db query
program i came up with an idea.

right now to load the table structure and make changes i have a tcl gui 
form.  i thought why not scrap that and use delphi for the structure 
change part of the gui. i'd keep the rest in tcl/tk.

basically how it works is i get the sqlite create table statement from 
sqlite_master and parse the hell out of it and feed it to the gui for 
structure viewing.  then i allow changes in the viewer and write to some 
.sql files for changing the table structure.

i thought delphi would be good because they have a nice tree control and 
a listbox with a checkbox next to each item in the listbox.  i thought i 
could load the structure in the tree view with items and sub-items and 
use the listbox with checkbox to keep track of the multi-field primary 
and unique constraints.

i am doing this because i want to add features like unique column 
constraints, multi-field primary and unique constraints and the ability 
to generate temp/temporary tables.  oh and i'd like to package my 
program with a star-kit to if possible...right now it uses freewrap.
maybe i can throw table view capability in there too.

on the plus side i have all the manuals and software needed for delphi.
on the minus side delphi and tcl cant communicate with one another like
c or c++ and tcl (free, open, and easy).  i dont think any communication 
is needed though.

am i missing any design issue that can break this program?


2.Very Different Ideas in ColorForth (Was interesting ideas in ColorForth)

m-coughlin wrote:
>    But how do you save your design so you can transfer it to
> silicon? There are so many steps in that process that are
> unknown to me that I don't even know what questions to ask to
> learn more.

The fab and some tools accept a standard GDS II format file
that describes a finished design in a way suitable for simulation
or fabrication.  Since Chuck has for many years only needed to
generate these files every few months he has said that files
are not a large part of (his) typical Forth applications.

That sort of statement has been very inflamator when some
people assume if he uses the word Forth he is talking about
them or if the statement was taken out of the "what Chuck Moore
said about what he does" and transposed into what someone else
is doing in an 'everything is a file' environment.

Over the years with more people contributing to the work many
other things have been extracted out or imported in standard
file formats.  There has been expansion to the file support
in the stand-alone colorforth and expanded file support in
the OS hosted versions over the years but I expect that Chuck
would say it remains a very small part of the Forth applications.

>    All these discussions of ColorForth skip over what must be
> obvious to everybody who uses it for designing new chips but

There is such a wide range of people with different backgrounds
using colorforth and cad tools in colorforth that many things
are not obvious to everybody.  Some of the people had never
seen Forth, some had decades of experience with Forth.  But
certainly people who get consistent training and who work
professionally with a tool regularly will see it differently
than the people who read discussions in c.l.f where old rumors
repeated, personal opinions, and things out of context make up
the meat of discussions on the subject until they spin off
into C or Pascal land and die.

I am more of a user than an implementor although I did create
a colorforth variant for f21.  At work I have taught new people
how to get started as users of colorforth and okad.  The
environment in a class or in professional work is very different
than a usenet political shouting festival. ;-)

But also these folks are more at the application and use level
than at the reverse engineer, document, or make a new system
level where folks are concerned with implementation issues
and details more than applications.  I have been around and
watched the history unfold but there are a team of professional
Forth programmers who are in charge of colorforth/okad
enhancement and I have to defer most internal technical details
to them. My experience is mostly as a user and teacher of the

And I do realize that c.l.f is more of an implementation
and internals discussion group than an application discussion
group and that Forth programmers in general are criticised
for this as we all know.  So it is natural that people will
bring up implementation issues for forth systems from any
time in the past as naturally as they are likely to discuss
the current version.  With most systems when they ask
questions the author or some experienced user will tell
people, that was problem in release 2.05 but as the history
notes show as fixed in 2.06 and I recommend the even more
recent 2.10 release etc.

> can't be known to anybody who does not use it that way. For
> example, there are MASM assembly listings that go with the
> ColorForth floppy disk files. Surely Chuck Moore would not use
> anything like MASM when he has his own Forth systems running.

The original colorforth scripting language was constructed in ok
and okad and that got assembler source in the mid-late 90s for
use with a tool like MASM.  When Chuck created the original
stand-alone colorforth as OS host to okad2 he created the
kernel with something like MASM I beleive and then did
the rest in colorforth.

By the time of the public release of colorforth the kernel was
now assembled with an assembler in colorforth but there may
have been hold over MASM listings for the original boot image.
I think Chuck thought some other people might find some
old MASM listings useful or instructive, but I don't know the
exact history, nor do I know exactly what files you are refering

Since that time other people have created other tools in various
formats including MASM and Albert did a disassembly with
his tools and made that available.  Someone else may know more
about the MASM files to which you refer.  They may have been
used by people who modified the floppy driver to work on some
other machine.  I never did that so I don't know those details.

> Are these MASM listings a disassembly of what is on the
> floppies?

I don't believe Chuck ever published the full MASM listing
of what he started with, and I don't believe that his MASM
listings were being used by the time colorforth was
released to the public, in fact I think they had been lost.

We might see a similar migration in the future from external
source to internal assembler to meta compilation as has
often been the case with many Forth creations.

> Suppose he agreed to work for a company that wanted a
> completely new original version of his software built from the
> ground up? What would he use to write it?

It is very hard for me to imagine Chuck agreeing to work for
a company that would tell him he had to rewrite a new version
in something other than colorforth.  But I could see him
working with other people who use other tools and follow
compatible specifications for cooperative work.  So he might
approve hiring someone else to do the work a different way
than he would if that looked good and in fact has.

I am pretty sure Chuck would want to use colorforth or nothing.
I have a hard time picturing anyone making him an offer that
he couldn't refuse if it meant he didn't get to work in
colorforth.  He is the kind of man to whom principles, especially
that he wants to do things the way he thinks is best and is going
to do that, are more important to him than money.  And money is
not a big issue for him any more anyway as his gamble on his
principles has worked out prettty well for him. He isn't going
to give in.

He is a strong proponent of individualism and self-reliance
and self-guidance by principle. He is the type of person with
low latent inhibition so he doesn't care about following others.
I think he likes to set an example of that type of fearless
individual who will go their own way.  If people follow his example
they don't follow him, they don't follow others, they lead their
own way.  At least that's my take knowing the man.  He seems
to like other experts who do things their own way too.  I makes
for teams that can exchange productive ideas and programming
methods and it works pretty well as it has in the past.

I think we think of that as the Forth community that we know
and that we think works pretty well.  Usenet on the other hand
is usenet and many people who have the most to say about Forth
and other languages never do Forth, unless complaining on usenet
is the definition of doing Forth. ;-)

Best Wishes

3.Very Different Ideas in ColorForth (Was interesting ideas in ColorForth)

m-coughlin wrote:
>      Because the weeks and months you could spend trying to do
> something with MASM based ColorForth would be made instantly
> obsolete when ColorForth written in Forth was published.

Huh?  What do the tools used to create the language have to do with 
writing code in that language?

>    "Usually" Is not good. How will it look if I try to show
> ColorForth to somebody and the first thing it does is crash?
> Telling them it "usually" works on "some" of my computers is
> just the same as saying it is a buggy kluge. I want to know
> exactly what standards it works with and what it does not. Does
> it skip over something a standard calls for or does it fail
> because some standard requirement is not followed by the
> hardware? I have six floppy disks with different versions of
> ColorForth. How do I label them so I have a chance to pick the
> computer they will work on?

I wouldn't bother.  Instead of dealing with different hardware, I would 
test and use under a virtual environment.  For free, anyone can get 
Microsoft's Virtual PC 2004, and I think that VMware also offers their 
product for free.  You could use Xen or Bochs or any number of other 
virtual environments and avoid all hardware issues.

That is if your goal is to use ColorForth.  If your goal is to set up 
artificial barriers to using it so that you can make a point, then 
virtualization won't help you there.  But you seem to be doing quite 
well there all on your own.

Or you could do what I did.  Before using virtualization to run 
ColorForth, I didn't have any hardware that could run it.  But I didn't 
need to execute the code in order to study it, surf the web to see what 
information was available, understand how it worked, and see if the 
various trade-offs in the design made sense to my work.  The computer 
between your ears runs ColorForth very well.

>     I have two versions that are identified as being for nVidia.
> But they sometimes work on computers that do not have nVidia
> video cards. Making a patch for some particular video card
> doesn't solve anything. We also need to know what was patched,
> why it was changed, when that change will work and when it
> woun't. If there is not a way to have ColorForth just boot up on
> every Pentium based motherboard then we need to know what the
> workarounds are to get it to work on somebody else's computer.

Normally, I would agree.  If ColorForth was a traditional open-source 
project with all the usual trappings (a constantly updated web site, a 
version control repository, bug tracking database, etc.), then chances 
are very good it run on a wider range of hardware without issue and the 
community of users using it would have collaborated on a database of 
platform work-arounds.

But to me, ColorForth isn't about a specific implementation, but a 
larger set of ideas.  And while I see using ColorForth as a cheap way to 
explore those ideas, the message I get with ColorForth isn't to 
standardize on a single specific implementation of the language, but to 
build a custom language of your own that is tuned for your application. 
  Your version of ColorForth might take some ideas from what Charles 
Moore has done, throw away ideas that are irrelevant to your work, and 
make new additions that make sense for what you need.

Forth has always been in some loose sense a language construction kit. 
We read the cliche' here in comp.lang.forth all the time-- that 
programming in Forth is extending the language to become the 
application.  In reality, that's true of programming in almost every 
language.  So with Forth, it's really a matter of degree-- how much one 
can extend the language.

ColorForth is no different.  If you view it as a set of ideas you could 
reuse in your own custom language, then you're not bound to the specific 
hardware decisions made in a specific implementation.

4.Modifying the arguments to a function is a bad idea

This discussion started in the thread:
"Help a beginner - simple lowercase to uppercase and so on function"
but it has actually nothing to do with the subject of that thread so I
start a new one.

My arguments for justifying the thesis in the subject line are:

o It makes the function not restartable
o Under the debugger you can't know what was the parameter you
   received when the function misbehaves. You can't debug it.
o The small gain in storage space is not worth the associated risks.

To my surprise, the eternal heathfield doesn't agree with this obvious 

He says to the first point:

 > You lost me. I am sure it is possible to construct a function in
 > which modifying its parameter makes it non-restartable, but you
 > don't /have/ to construct functions that way.

Well, apparently he doesn't get it. Suppose a function

int fn(int a)
	// some code
	a = 56;
	// more code

After that assignment it is impossible to go to the first line of the
function and restart it, since the original value of a is lost.

This is completely obvious but somehow not obvious to some.

To the second point, he argues ( I cite again the second point
for clarity)

 > o Under the debugger you can't know what was the parameter
 >   you received when the function misbehaves. You can't debug it.
<end of jn quote>

Maybe you can't, but I can - by setting a breakpoint at an
appropriate place and making a note of the value before the mod.
<end of heathfield>

The obvious situation where the function is called 4765 times
before it crashes doesn't occur to him. Maybe because he has never been
in the frustrating situation of trying to know what is the specific
parameter that makes the function crash. :-)

He continues:
What risk do you see in:

void intcopy(int *s, int *t, int term)
   while((*s++ = *t++) != term) {}
< end of heathfield>

I see MANY risks in that construct, the first and foremost
is that "t" is a vector of integers that is MISSING the
"term" terminator!

Of course THAT "can't happen", and heathfield doesn't even consider
that case.

BUT, let's suppose that this happens, since in the real world,
bugs DO appear.

How you will see the effects of that?

(1) The program as written will crash when it arrives at the end of
available memory . Since you do not have the original data, you
can't figure out what parameters were passed in.

(2) The program will find a random integer in memory that
corresponds to "term", after having overwritten a lot of memory.
That function will return as if nothing had happened leaving
the rest of the software in an unknown state. Since this depends
on the contents previously stored in unknown data areas, the
program will (or will not) go on, maybe crashing sometimes
or (worst) never crashing but giving *sometimes* strange results or
crashes hours later.

Another obvious problem with the function above is that no SIZE
information is passed to limit the copy, so that if "s" points to
an area too small to receive "t" a buffer overflow will happen.

That has in principle nothing to do with the modification of the
parameters but having the parameters still available it would
allow you to see the corresponding address and you can figure out
its size and location within the debugger.

Actually, I wanted to highlite this problem because I consider that
functions like "intcopy" are the ideal example of how NOT to program
in C.

o Function modifies its parameters. Not restartable, not debuggable.
o No error analysis at all (return value void)
o The slightest error in the calling function when passing the
   parameters leads to debugging nightmares.

It is funny that another "regular" (Mr Ben Pfaff) says:

<quote Mr Pfaff>
I would say that the latter is riskier, because there are more
entities for me to keep track of as I read it.  It is easier to
understand the behavior of three variables than five.
<end of quote>

The brain of Mr Pfaff has difficulties reading:

 > void intcopy(int *s, int *t, int term)
 > {
 >   int *u = s;
 >   int *v = t;
 >   while((*u++ = *v++) != term) {}
 > }

Imagine the problems Mr Pfaff would have if we pass size information
to make better designed software!

I can only recommend to him to stop programming. Reading NO variables
at all is surely even easier to do.



a)	Do not modify the parameters of a function. It is a bad idea.

b)	Think about the debugging of the functions when you write them.
	If you do that, you will avoid monstrosities like the above
c)	Do not follow the advise of heathfield (and co)...


6. good idea

7. Very good idea, thanks autor

8. [OT] could it to be a good idea?

Return to c


Who is online

Users browsing this forum: No registered users and 62 guest