Searching \ for '[OT]: Beginner C question' in subject line. ()
Make payments with PayPal - it's fast, free and secure! Help us get a faster server
FAQ page: www.piclist.com/techref/language/index.htm?key=c
Search entire site for: 'Beginner C question'.

Exact match. Not showing close matches.
PICList Thread
'[OT]: Beginner C question'
2001\04\28@114509 by Thomas N

picon face
Hi everyone,

I am three global variables num1, num2, and num3.  I am looking for a
sorting function to sort them in ascending order.  Please help!

If I declare those 3 variables as global, do I have to pass their values to
a function?  Can I have, void sort(void), and in this function, it gets the
value of num1, num2, and num3 and put them back in num1, num2, and num3 in a
ascending order?

Would you please tell me where the C community is, so I don't have to post
an OT here?

Thank you very much!
Thomas




_________________________________________________________________________
Get Your Private, Free E-mail from MSN Hotmail at http://www.hotmail.com.

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@115551 by Dale Botkin

flavicon
face
On Sat, 28 Apr 2001, Thomas N wrote:

> If I declare those 3 variables as global, do I have to pass their values to
> a function?  Can I have, void sort(void), and in this function, it gets the
> value of num1, num2, and num3 and put them back in num1, num2, and num3 in a
> ascending order?

Yep.  If they're global you don't have to pass them to the function.  I've
seen people write that global variables are bad form...  but for the life
of me I can't see why, I use them where I need to.

> Would you please tell me where the C community is, so I don't have to post
> an OT here?

Are you writing PIC code in C?  If so I do't think it's OT.  There are
several of us here who code in C for PICs.

Dale
---
The most exciting phrase to hear in science, the one that heralds new
discoveries, is not "Eureka!" (I found it!) but "That's funny ..."
               -- Isaac Asimov

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@121012 by Simon Redwood

flavicon
picon face
Reply To: "Simon Redwood" <spam_OUTspredwoodTakeThisOuTspamsri-net.demon.co.uk>
X-Mailer: ELM [version 2.4ME+ PL60 (25)]
MIME-Version: 1.0
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit

ansu c provides a sort function (qsort if think it is ), you just need to supply if function declare
hwo the differences are made.  ALthough it primilarly used for sort complex
data types.

int mysortfunc(void *a, void *b)
{
       if (int *)a/b is greater
               return 1;
       else
               return 0;
}

qsort(array, sizeof(int), (int (*)())mysortfunc);


Probably a bit OTT for sort three integers but is extremely flexible.


{Quote hidden}

--
Regards,
Simon

{ ICQ#:         12226096                        }
{ Email:        .....spredwoodKILLspamspam@spam@sri-net.demon.co.uk   }
{ Internet:     http://www.sri-net.demon.co.uk         }

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@122034 by Thomas N

picon face
Yes, I heard people say that using global variable to pass a value is bad,
but I don't see the reason why either
Thomas

{Quote hidden}

_________________________________________________________________________
Get Your Private, Free E-mail from MSN Hotmail at http://www.hotmail.com.

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@122501 by Andy N1YEW
picon face
Heres you help...


----- Original Message -----
From: Thomas N <thomasn101spamspam_OUTHOTMAIL.COM>
To: <@spam@PICLISTKILLspamspamMITVMA.MIT.EDU>
Sent: Saturday, April 28, 2001 8:43 AM
Subject: [OT]: Beginner C question


> Hi everyone,
>
> I am three global variables num1, num2, and num3.  I am looking for a
> sorting function to sort them in ascending order.  Please help!

its easy

>
> If I declare those 3 variables as global, do I have to pass their values
to
> a function?
NO.

> Can I have, void sort(void), and in this function, it gets the
> value of num1, num2, and num3 and put them back in num1, num2, and num3 in
a
> ascending order?

yes

> Would you please tell me where the C community is, so I don't have to post
> an OT here?

I would but I dont know


> Thank you very much!
> Thomas

The algo is simple but i forgot it. :(

I can send you it later if you want

Andy

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@130921 by Mark Benson

picon face
Global variables are indeed bad form and should be avoided whenever
possible.  This distinction becomes clear quickly when working on a complex
system with multiple modules.  When the system increases in size to the
point such that the mind has difficulty in wrapping itself around that
system, global variables become hard to keep track of.  It's far too easy to
forget all the places where global variables are dealt with in the system
structure; especially when the system undergoes vast change or deviation
from the original course of action during the development process.

Another situation where global variables should especially be avoided is
when working with multiple programmers on the same project (open source, or
large systems).  It's hard to keep everyone accountable to use the variables
properly.  For instance, someone might not know that a byproduct of calling
a certain function is that it changes the value of a global variable.  This
could prove harmful especially if not clearly documented.

It is also much easier to describe software to someone who might need to
maintain or understand it if the complexities inherent in the
cross-functional use of global variables are not there.  Encapsulating
functionality and data instead of tinkering with global variables usually
provides cleaner code that is easier to understand.

The antithesis of the rampant use of global variables is Object Oriented
Design which is a bit difficult in languages that are not centered around
such a concept.  It is good however, to know about the theory behind OOD.
It helps to form a general knowledge base that increases the quality of our
software design when using other languages that are not really Object
Oriented languages.

At the least this much is clear to me: explicitly passing values to a
function should always be a priority over implicitly changing the values of
globals. Encapsulating data provides way to a cleaner and less error-prone
system.

regards,

Mark Benson



{Original Message removed}

2001\04\28@135143 by Dale Botkin

flavicon
face
On Sat, 28 Apr 2001, Mark Benson wrote:

> Global variables are indeed bad form and should be avoided whenever
> possible.  This distinction becomes clear quickly when working on a complex
> system with multiple modules.  When the system increases in size to the
> point such that the mind has difficulty in wrapping itself around that
> system, global variables become hard to keep track of.  It's far too easy to
> forget all the places where global variables are dealt with in the system
> structure; especially when the system undergoes vast change or deviation
> from the original course of action during the development process.

Of course it would be difficult to work up a PIC based project of this
scale.

> Another situation where global variables should especially be avoided is
> when working with multiple programmers on the same project (open source, or
> large systems).  It's hard to keep everyone accountable to use the variables
> properly.  For instance, someone might not know that a byproduct of calling
> a certain function is that it changes the value of a global variable.  This
> could prove harmful especially if not clearly documented.

I can see the point here, but again, usually not a problem on a PIC based
project -- ceratinly not any of mine.

> It is also much easier to describe software to someone who might need to
> maintain or understand it if the complexities inherent in the
> cross-functional use of global variables are not there.  Encapsulating
> functionality and data instead of tinkering with global variables usually
> provides cleaner code that is easier to understand.

I find, however, that there may be a stiff price to pay for this in small
systems.  In fact, there are situations in which I can't see how it would
be possible to avoid global variables.  Example:  I'm working on a project
in which there are variables that need to be updated by interrupt routines
and used in main() and at least one other function.  I may not be a
degreed professional programmer who's done this for a living for years,
but I don't see how you could do this without using global variables.  I
think a blanket statement that globals are evil is a little simplistic,
and certainly applicable to a much lesser degree when working with small
embedded systems.

> At the least this much is clear to me: explicitly passing values to a
> function should always be a priority over implicitly changing the values of
> globals. Encapsulating data provides way to a cleaner and less error-prone
> system.

I would agree with this approach where it can be used.  In fact, your
statements are probably the most reasonable I've heard...  in the past
there have been those who I understood to have the opinion that one should
NEVER use a global variable, which is a position with which I strongly
disagree.

Dale
---
The most exciting phrase to hear in science, the one that heralds new
discoveries, is not "Eureka!" (I found it!) but "That's funny ..."
               -- Isaac Asimov

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@143205 by Mark Benson

picon face
>> Global variables are indeed bad form and should be avoided whenever
>> possible.  This distinction becomes clear quickly when working on a
complex
>> system with multiple modules.  When the system increases in size to the
>> point such that the mind has difficulty in wrapping itself around that
>> system, global variables become hard to keep track of.  It's far too easy
to
>> forget all the places where global variables are dealt with in the system
>> structure; especially when the system undergoes vast change or deviation
>> from the original course of action during the development process.
>
>Of course it would be difficult to work up a PIC based project of this
>scale.
>
>> Another situation where global variables should especially be avoided is
>> when working with multiple programmers on the same project (open source,
or
>> large systems).  It's hard to keep everyone accountable to use the
variables
>> properly.  For instance, someone might not know that a byproduct of
calling
>> a certain function is that it changes the value of a global variable.
This
>> could prove harmful especially if not clearly documented.
>
>I can see the point here, but again, usually not a problem on a PIC based
>project -- ceratinly not any of mine.
>

You are right on these points.


{Quote hidden}

I may have gone a little too far in seeming to make a "blanket statement"
about how global variables should be used.  I did not mean to say that they
should never be used.  Global variables are needed just like you said in
certain situations such as global timer variables that need to be updated in
the interrupt routines, and used in main() or other functions.  Uses of
global variables in circumstances such as these are good and neccessary uses
because the interrupt needs to have access to them as soon as the interrupt
occurs.

I talked about the problem of describing the software because some
experience that I have from working on a few industrial safety control
devices that require a large amount of documentation.  Usually safety
products such as these require documenting exactly how global variables are
used.  Using globals are fine as long as they are not overused or misused.


>> At the least this much is clear to me: explicitly passing values to a
>> function should always be a priority over implicitly changing the values
of
>> globals. Encapsulating data provides way to a cleaner and less
error-prone
>> system.
>
>I would agree with this approach where it can be used.  In fact, your
>statements are probably the most reasonable I've heard...  in the past
>there have been those who I understood to have the opinion that one should
>NEVER use a global variable, which is a position with which I strongly
>disagree.
>
>Dale

We definitely agree on this.  Like you, I also would disagree with someone
who advocated complete abolition of global variables from an embedded
system.

Mark

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@150200 by Bob Ammerman

picon face
For PIC sized programs globals are not only not bad, they are just about
necessary.

When you start writing programs in the 10000+ lines range globals give you
fits because they break 'information hiding' rules.

Bob Ammerman
RAm Systems
(contract development of high performance, high function, low-level
software)

{Original Message removed}

2001\04\28@154510 by Nick Thompson

flavicon
face
> At the least this much is clear to me: explicitly passing values to a
> function should always be a priority over implicitly changing the values of
> globals. Encapsulating data provides way to a cleaner and less error-prone
> system.
>
> regards,
>
> Mark Benson

once you actually get it built =).

it's worth noting that most of the people teaching and writing books
about the importance of encapsulation can't actually code their way
out of a wet paper bag.  you hear less about the evils of modularity,
perhaps because most of the people who worry about it are busy writing
code rather than prose.  FWIW, here's my experience.

i learned software engineering too, it took me years to recover my
ability to write programs quickly because i was spending all my time
changing the oh-so-important interfaces (mostly with only one
implementation and one client, hmmm) rather than writing the code to
solve the problem.  i shudder to think how many half-completed
interface specifications i left behind because while i was (trying to)
solve the problem of "build the ultimate reconfigurable X", someone
else was just building X.  it turned out nobody wanted my properly
designed X - and who can blame them, since the crude get-the-job-done
X would solve 90% of the problems out of the bag, 97% with a little
custom tweaking.  meanwhile, i was on the third redesign of the
"cleaner and less error prone version", without any of the real-world
user experience that the quick-and-dirty people were getting and could
presumably roll into their next version (*if* one were needed).  as a
bonus, this style turns out to be a lot more fun since you actually
get to play with a working system for most of the time, and this
relatively quick gratification also helps to keep development rolling
for a lot of people.

folks who prefer to build castles in the air rather than getting their
hands dirty will show themselves by attempting to delay the first
functioning prototype because they don't like its internal structure -
unless they're very experienced architects these people make poor
teammates.  one of my hardest lessons was that interfaces are not code
and that if the code requires a nasty and brutish control structure,
my habit is to shy away from writing it and work on an interface to
hide the nastiness instead.  eventually i have to write that goto
anyway, it would have been better just to get it over with and move
on.  sometimes i can even complicate the nastiness by attempting to
put an abstraction over it - this is sort of like putting dim lighting
and draperies in your machine shop over by the power saw.  sure the
shop looks cleaner and prettier, but the first stranger who has to use
it is going to the hospital.

i think it was john ousterhout who pointed out that a program which
sort of works, but is riddled with bugs, still has fewer bugs than the
one which isn't written yet.

as someone else pointed out, most pic programs are simpler than a
single object in the sort of large, long-lived system where these
design methods are needed anyway.  if it helps you sleep at night you
can think of the pic as one object, and the globals as the instance
vars for that object.  you can actually write large scale programs
this way too - use globals while you're getting the module working,
but with a little discipline you can make them easy to find and turn
into structures if you need to turn the prototype into a module in
a larger system.

   nick

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@161912 by uter van ooijen & floortje hanneman

picon face
> it's worth noting that most of the people teaching and writing books
> about the importance of encapsulation can't actually code their way
> out of a wet paper bag.  you hear less about the evils of modularity,
> perhaps because most of the people who worry about it are busy writing
> code rather than prose.  FWIW, here's my experience.

(Double-check: yes, there is [OT]: in the subject line)

Anything that is taken too far will do more bad than good, but IMHO a lot of
programmers (especially the beginners) could use so more encapsulation. And
that does not mean just starting to wrap everything in objects, it means
some hard thinking, for instance about wat should be visible/accesible and
what should not. But if your experience learns you that this does not apply
to you by all means follow you own path. What is often said for standards
holds equally for programming paradigma's: design your own, then identify
the one that fits what you have come up with.

Wouter

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\28@205947 by Kevin Maciunas

flavicon
picon face
On 28 Apr 2001 12:34:59 -0700, Nick Thompson wrote:
> > At the least this much is clear to me: explicitly passing values to a
> > function should always be a priority over implicitly changing the values of
> > globals. Encapsulating data provides way to a cleaner and less error-prone
> > system.
> >
> > regards,
> >
> > Mark Benson
>
> once you actually get it built =).
>
> it's worth noting that most of the people teaching and writing books
> about the importance of encapsulation can't actually code their way
> out of a wet paper bag.  you hear less about the evils of modularity,
> perhaps because most of the people who worry about it are busy writing
> code rather than prose.  FWIW, here's my experience.
>


OK, I both teach this stuff and have written about it AND I also code.
A lot - and PICs and Atmel AVRs and a few other embedded things.  The
important thing to get out of the last 30 years of Computer Science
research in this area is that modularity is "a good thing"(TM).  This
does NOT mean, however, that you must write the code for your PIC code
in Ada or some other language which directly supports all the
programming language infrastructure for this.  My PIC stuff is written
in C (CCS C to be specific) or PIC assembly.  The key issue is how you
design the bits and pieces.  I too have many students who endlessly
stuff around trying to design a "perfect" interface to some component in
a piece of software they are developing.  The standard advice I give is
to just do it and evolve the interface as needed.  When they have some
experience under their belts, they tend to choose wisely initially :-).
For my own part, I've found that most of the PIC projects I've done have
been able to leverage significant existing code I've written for earlier
projects.   The present project is a controller for a home brew (as in
beer) mashing set up.  Has an LCD, keypad, temp sensors, pump (PWM)
control and heater control (PWM again).  The host CPU is a 'f877 and
I've been able to pinch my LCD, keypad, DS1820, RS-232 debug "what the
hell is it doing??" code from other projects.  This has been trivial
because these components were built with a well defined interface - not
that I sweated hours over it - the interfaces certainly changed over
time!  The nice aspect to this approach is the usual one - you can get
something up and running with already debugged infrastructure into which
you can start to build the actual target application quickly (well,
maybe not all that quickly - I need to get some time together first!).

I suspect, however, that the above is pretty much what everyone does
anyway, experience is what makes a good [software] engineer.

$0.02
/Kevin


--
Kevin J. Maciunas              Net: KILLspamkevinKILLspamspamcs.adelaide.edu.au
Dept. of Computer Science      Ph : +61 8 8303 5845
University of Adelaide         Fax: +61 8 8303 4366
Adelaide 5005 SOUTH AUSTRALIA  Web: http://www.cs.adelaide.edu.au/~kevin

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


2001\04\29@123715 by Roman Black

flavicon
face
Mark Benson wrote:
>
> >> Global variables are indeed bad form and should be avoided whenever
> >> possible.

> >I can see the point here, but again, usually not a problem on a PIC based
> >project -- ceratinly not any of mine.


At the risk of sounding argumentative, surely all
tools are best used by a skilled person. Like a
screwdriver SHOULD be used to turn screws, but I
feel real justified also using one to open a tin of
paint.:o)

When I worked on a PC programming team my job was
to make the graphics engine and small utilities, and
yes I used globals when they were best and even gotos.
I also made the fastest and smallest C code out of the
group. And it worked well.

Some carpenters swear by the nail gun and do great
work, other use nothing but glued dowel pins, both
think they are right...

So especially on a PIC forum where most programs
are small and specialised the university model
of "globals==bad || gotos==bad" must be considered
as just a starting point, not the meaning of life.
I think in all fields the rules you teach an
impressionable student are very different to the
rules an experienced professional lives by. :o)
-Roman

--
http://www.piclist.com hint: The PICList is archived three different
ways.  See http://www.piclist.com/#archives for details.


2001\04\29@141431 by Thomas N

picon face
Can't believe my "global" variable question gets so many responses!

I have another problem.  I have simple function below which check to see if
the argument enter at the command line is a valid number.  This function
work fine with possitive integer, but I want it to accept floating point
number as well.  The floating point number can include "+" and "-" sign, and
decimal point.

Thank you in advance!
Thomas

/********************************************************************
* check_valid_number:   this function checks each character in      *
*                       string to ensure that it is a valid         *
*                       digit.  It return 1 if string makes a       *
*                       valid number, zero otherwise.               *
*                                                                   *
* char_string       :   a string to be tested if it is a valid      *
*                       digit                                       *
*                                                                   *
* Return        :       1 if string makes a valid number,           *
*                       zero otherwise.                             *
********************************************************************/

int check_valid_number(char *char_string)
{
       int     count, length;

/* count the number of character in the string */
       length = strlen(char_string);

/* go through each character and check whether it is a valid digit */
       for(count = 0; count < length; count++)
               if (!isdigit(*(char_string + count)))
                       return 0;

/* return 1 if it is a valid number */
       return 1;
}
/* end of check_valid_number */




{Quote hidden}

_________________________________________________________________________
Get Your Private, Free E-mail from MSN Hotmail at http://www.hotmail.com.

--
http://www.piclist.com hint: The PICList is archived three different
ways.  See http://www.piclist.com/#archives for details.


2001\04\29@142654 by Joan Ilari

flavicon
face
Roman Black wrote :

>
>  Some carpenters swear by the nail gun and do great
>  work, other use nothing but glued dowel pins, both
>  think they are right...
>
>  So especially on a PIC forum where most programs
>  are small and specialised the university model
>  of "globals==bad || gotos==bad" must be considered
>  as just a starting point, not the meaning of life.
>  I think in all fields the rules you teach an
>  impressionable student are very different to the
>  rules an experienced professional lives by. :o)
>

I agree with you, Roman. One thing is to define a set of
rules to improve program readability and a completely
different to be slave of these rules. Sometimes it can
be worth breaking the rules of "structured programming"
(for instance, when you detect an error inside 20 nested
structures, a plain "goto" is wonderful).

Joan

--
http://www.piclist.com hint: The PICList is archived three different
ways.  See http://www.piclist.com/#archives for details.


2001\04\30@115407 by Dipperstein, Michael

face picon face
Thomas,

Look at the atof function in math.h.  It should even give you the value of a
valid entry.

-Mike

{Original Message removed}

2001\04\30@171800 by Peter L. Peres

picon face
>For PIC sized programs globals are not only not bad, they are just about
>necessary.

Not to mention the savings in code space due to not passing reference
arguments to the subroutines.

Peter

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email RemoveMElistservspamTakeThisOuTmitvma.mit.edu with SET PICList DIGEST in the body



'[OT]: Beginner C question'
2001\05\01@200725 by Bill Westfield
face picon face
   I have another problem.  I have simple function below which check to
   see if the argument enter at the command line is a valid number.  This
   function work fine with possitive integer, but I want it to accept
   floating point number as well.  The floating point number can include
   "+" and "-" sign, and decimal point.

I'll take a crack at this, even thought it looks like a homework problem.
(should have been due by now, right?  Maybe that's a general way to handle
this sort of thing...)


   /********************************************************************
   * check_valid_number:   this function checks each character in      *
   *                       string to ensure that it is a valid         *
   *                       digit.  It return 1 if string makes a       *
   *                       valid number, zero otherwise.               *
   *                                                                   *
   * char_string       :   a string to be tested if it is a valid      *
   *                       digit                                       *
   *                                                                   *
   * Return        :       1 if string makes a valid number,           *
   *                       zero otherwise.                             *
   ********************************************************************/

   int check_valid_number(char *char_string)
   {
           int     count, length;

   /* count the number of character in the string */
           length = strlen(char_string);

   /* go through each character and check whether it is a valid digit */
           for(count = 0; count < length; count++)
                   if (!isdigit(*(char_string + count)))
                           return 0;

   /* return 1 if it is a valid number */
           return 1;
   }
   /* end of check_valid_number */


The "meat" of the routine is sort of classic "ugly" C code:

           for(count = 0; count < length; count++)
                   if (!isdigit(*(char_string + count)))
                           return 0;
           return 1;

While there's nothing WRONG with this, exactly, and it's not really hard to
read, it has been written 'concisely' to the point where it is less than
obvious how to extend it in the fashion you ask about.  First of all, it's
not "blocked" to add statements to, and secondly, the way it checks for
ILLEGAL character make it harder to extend algorithmicly.   One way to
extend this would be:

       for(count = 0; count < length; count++) {
           char thischar = *(char_string+count);
           /*
            * check for legal non-digit characters
            */
           if (thischar == '.')
               continue;       /* decimal ok - continue loop */
           if (thischar == '+')
               continue;       /* plus sign ok - continue loop */
           if (thischar == '-')
               continue;       /* minus sign ok - continue loop */
           /*
            * having eliminated "special" characters, the only remaining
            * legal characters are digits.
            */
           if (!isdigit(thischar))
               return 0;
       }
       /*
        * We looped through all characters and didn't find anything illegal
        * Therefore the number is OK.
        */
       return 1;


I don't like the extra variables, or the mixture of "positive and negative
logic", and I probably would have written something like:

       while ((thischar = *char_string++) != 0) {
           /*
            * check for legal non-digit characters
            */
           if (thischar == '.')
               continue;       /* decimal ok - continue loop */
           if (thischar == '+')
               continue;       /* plus sign ok - continue loop */
           if (thischar == '-')
               continue;       /* minus sign ok - continue loop */
           if (isdigit(thischar))
               continue;       /* digits are legal */
           /*
            * other checks for legal characters go here.
            */

           return 0;           /* illegal character - get out now */
       }
       /*
        * We looped through all characters and didn't find anything illegal
        * Therefore the number is OK.
        */
       return 1;

This eliminates both "length" and "count" (which I don't think would be
optimized away by anything but the most advanced compiler.)  Use of *p++ is
likely to be well-optimized to irregularities in most processors instruction
sets, since it's very common.  Some people object to assignments in the
conditional of a while statement, and some people don't like "continue", but
that's what I'd have done.  You COULD use logical operators:
           if ((thischar == '.') ||
               (thischar == '+') ||
               (thischar == '-'))
               continue;       /* assorted puncuation ok - continue loop */

Or even (from the original)
           for(count = 0; count < length; count++)
                   if (!(isdigit(*(char_string + count)) ||
                         (thischar == '.') || (thischar == '+') ||
                         (thischar == '-')))
                         return 0;

But the code is very likely to be the same, and it has the same sort of
"difficult to extend" problems as the original, and starts to get difficult
to read easilly.  IMO.

BillW

--
http://www.piclist.com hint: To leave the PICList
piclist-unsubscribe-requestEraseMEspam.....mitvma.mit.edu


2001\05\01@202617 by Andrew Warren

flavicon
face
William Chops Westfield <EraseMEbillwspamcisco.com> wrote:

> I'll take a crack at this, even thought it looks like a homework
> problem.
> ....
> for(count = 0; count < length; count++)
>   if (!(isdigit(*(char_string + count)) ||
>                       (thischar == '.') ||
>                       (thischar == '+') ||
>                       (thischar == '-'))) return 0;

[and a couple of other implementations of the same algorithm]

Bill:

If it IS a homework assignment, your code wouldn't get an "A"; it
identifies each of the following as a legal number:

   3.2.1
   3-+1
   -
   1++

   etc.

-Andy


=== Andrew Warren --- RemoveMEaiwEraseMEspamEraseMEcypress.com
=== Staff Systems Engineer, IPD
=== Cypress Semiconductor Corporation

--
http://www.piclist.com hint: To leave the PICList
RemoveMEpiclist-unsubscribe-requestspam_OUTspamKILLspammitvma.mit.edu


2001\05\01@204536 by Brian Reed

flavicon
face
To the original poster,

This:
    isdigit(*(char_string + count))
is a bit more readable when written like this:
    isdigit(char_string[count])

- Bri

--
http://www.piclist.com hint: To leave the PICList
RemoveMEpiclist-unsubscribe-requestTakeThisOuTspamspammitvma.mit.edu


2001\05\01@204724 by Bill Westfield

face picon face
   >   if (!(isdigit(*(char_string + count)) ||
   >                       (thischar == '.') ||
   >                       (thischar == '+') ||
   >                       (thischar == '-'))) return 0;

   [and a couple of other implementations of the same algorithm]

   If it IS a homework assignment, your code wouldn't get an "A";

Oh good. :-)  The above won't even compile, of course, since I cut&pasted
without changing the "thischar"s back to char_string references.


   it identifies each of the following as a legal number:
       3.2.1    3-+1    -    1++

Hey!  Positional dependency and repetition detection weren't in the
specification *I* got, man.  (An interesting illustration of Something in
itself, I guess...)

:-)
BillW

--
http://www.piclist.com hint: To leave the PICList
EraseMEpiclist-unsubscribe-requestspamspamspamBeGonemitvma.mit.edu


2001\05\01@213815 by Douglas Wood

picon face
Why write your own routine? Just use 'atof()'.

Douglas Wood
Software Engineer
RemoveMEdbwoodKILLspamspamkc.rr.com

Home of the EPICIS Development System for the PIC and SX
http://epicis.piclist.com

{Original Message removed}

2001\05\02@012016 by Thomas N

picon face
Gentlemen,

I got it!  It works well so far.  I don't know if there is any hole in this
function or not.  Can you think any situation where it won't work?!

Thanks for playing!
Thomas

/****************************************************************
* check_valid_number : this function checks each character in   *
*                       string to ensure that it is a valid     *
*                       digit.  It return 1 if string makes a   *
*                       valid number, zero otherwise.           *
*                                                               *
* char_string   :       a string to be tested if it is a valid  *
*                       digit                                   *
*                                                               *
* Return        :       1 if string makes a valid number,       *
*                       zero otherwise.                         *
***************************************************************/

int check_valid_number(char *char_string)
{
  int count, length,
       valid_digit = 0,
       decimal_count = 0;

/* count the number of character in the string */
  length = strlen(char_string);

/* go through each character and check
  whether it is a valid digit */
  for(count = 0; count < length; count++)
  {
  if (isdigit(*(char_string + count)) == 0)
  {
     valid_digit = FALSE;
/* check the leading "+", "-", and "." */
    if(count == 0)
    {
       if((char_string[0] == '-') || (char_string[0] == '+')
                            || (char_string[0] == '.'))
       {
       valid_digit = TRUE;
       if (char_string[0] == '.')
         decimal_count = 1;            /* make sure there is
                                         no extra decimal points! */
       }
    } /* end of checking leading character */
/* check for decimal points */
 else
   if((*(char_string + count) == '.') &&
       (decimal_count != 1))
       {
            valid_digit = TRUE;
            decimal_count = 1;
       }
       if(valid_digit == FALSE)
          return 0;                    /* return 0 if invalid */
     } /* end of if(isdigit(..)) */

  }    /* end of for(count...) loop */
       return 1;
}
/* end of check_valid_number */

{Quote hidden}

>{Original Message removed}

2001\05\02@022103 by Scott Dattalo

face
flavicon
face
On Wed, 2 May 2001, Thomas N wrote:

> Gentlemen,
>
> I got it!  It works well so far.  I don't know if there is any hole in this
> function or not.  Can you think any situation where it won't work?!

Thomas,

I may be biased, but <OLIN>I don't like this approach because it's difficult to
follow and maintain </OLIN>. If you care to hear some opinions and get inundated
with information then read on...

You may wish to check out a parser I wrote a long time ago:

http://www.dattalo.com/parser.html

It's a C++ program that parses numbers among other things. To be honest, if I
were to re-write it I'd just use LEX/YACC (or bison and flex). You can check out
the gpsim or gpasm or any number of open source projects for implementations of
parsers of this type. However, I realize that this stray far from the "Beginner
C" solution.

Another parser that I'm currently writing is a "one line assembler". I'm using
this to read PIC assembly code and converting it into a format called
"pCode". It's part of the SDCC PIC port.

http://www.dattalo.com/gnupic/sdcc.html

You may wish to look at this one file. But, there's a bunch of stuff in there
that hides the parser:
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/sdcc/sdcc/src/pic/pcodepeep.c

This parser is structure like flex/bison. The raw data is first broken into a
stream of tokens. Then the "syntax" is checked by looking for the proper
sequence of tokens.

For your example, you could define the basic tokens:

SIGN
INTEGER
DECIMAL
EXPONENT


Then the syntax for valid numbers could be represented as

INTEGER
INTEGER DECIMAL
DECIMAL INTEGER
INTEGER DECIMAL INTEGER
SIGN INTEGER
etc.


You would leave out invalid combinations like

DECIMAL DECIMAL


Now the easiest approach for implementing this is to create a case statement for
each token type. Although for four tokens, I'd be tempted to if/else it. Each
time a valid token is found, put it into a token array. When the end of the
string is reached, then compare the elements of the token array to the valid
token sequences.

A more complicated approach is to use recursion and state tables (machines).

Maybe if you write two versions, you'll get two A's!

Scott

--
http://www.piclist.com hint: PICList Posts must start with ONE topic:
[PIC]:,[SX]:,[AVR]: ->uP ONLY! [EE]:,[OT]: ->Other [BUY]:,[AD]: ->Ads


2001\05\02@131418 by jamesnewton

face picon face
Maybe someone who is better at C++ than I (I do C well and I like OOP but
C++ sometimes gets me) can explain what handles the "execute" message for
variables and FOPs in Scott's parser program.

---
James Newton (PICList Admin #3)
@spam@jamesnewton@spam@spamspam_OUTpiclist.com 1-619-652-0593
PIC/PICList FAQ: http://www.piclist.com or .org

{Original Message removed}

2001\05\02@134959 by jamesnewton

face picon face
Oh, never mind, I found it in the parser.h file...

...seems like it wouldn't take much to combine this with Nik's Constmuldiv
code generator and some of the code from the piclist.com code library to
make a little expression evaluator for the web site...

Any interest?

---
James Newton (PICList Admin #3)
spamBeGonejamesnewtonspamKILLspampiclist.com 1-619-652-0593
PIC/PICList FAQ: http://www.piclist.com or .org

{Original Message removed}

More... (looser matching)
- Last day of these posts
- In 2001 , 2002 only
- Today
- New search...