HDTenEightyP/NetNews huggingface dataset:
From: IA8@psuvm.psu.edu (Alan R. Heyd)
Newsgroups: comp.lang.c
Subject: Rounding floats to integers
Date: 9 Nov 92 18:47:11 GMT
Organization: Penn State University

Is there a C routine that will round off floating point numbers
to the nearest integer.  K&R says that floats are converted to
integers by removing the fractional part, however, I could not
find mention of a routine which rounds to the nearest integer.
What I do now is add 0.5 to the float before it is converted to
an integer, for example:

          int i;
                                 /* Using Turbo C on and IBM PC: */
          i = 6.0 / 0.3;         /*   i = 19                     */
          i = 6.0 / 0.3 + 0.5;   /*   i = 20 as expected         */

is there a better way?

Thanks,

Alan Heyd
ia8@psuvm.psu.edu
Newsgroups: comp.lang.c
From: msb@sq.sq.com (Mark Brader)
Subject: Re: Help.  (Unix C)
Supersedes: <1992Nov6.035051.16838@sq.sq.com>
Organization: SoftQuad Inc., Toronto, Canada
Date: Fri, 6 Nov 92 05:59:34 GMT

[Corrected version; apologies if you already read the now-cancelled original.]

> > you could do simply
> > 
> >      return (ptr->item1 - ptr->item2);

> This works for intgers, not floats (sorry)

No, this works only for types that are (a) *narrower* than int, and
(b) signed.  Therefore it should not be used for this application!

If item1 and item2 are 16-bit ints, try it on the case where their
respective values are 20000 and -20000.  If they are 32-bit ints,
append 00000 to each of these, and then try it.  If you are lucky,
you are on an implementation that detects arithmetic overflow and
your program terminates.  More likely the comparison just returns
the wrong result.

Verbose as it may seem to some, the approach of doing two separate
comparisons really is the only safe one.
-- 
Mark Brader, SoftQuad Inc.,			"Verbose better."
Toronto, utzoo!sq!msb, msb@sq.com		    -- David M. Sherman

This article is in the public domain.
Newsgroups: comp.lang.c
From: root@fincomp.raidernet.com (Neal McClain)
Subject: Re: The Correct Way To Write C if-Statements
Organization: Financial Computers Corp., Murfreesboro, TN
Date: Fri, 06 Nov 1992 15:00:40 GMT

In <140742@lll-winken.LLNL.GOV> booloo@framsparc.ocf.llnl.gov (Mark Boolootian) writes:

Phil - This piece finally explained to me the origin of the word CRAP,
so I thought I'd pass it along to you.  I hacked a bunch of it - the part
which described this guy's opinion on good C code layout - on the assumption
that you wouldn't pay any attention to it anyway (I didn't).

If you do want to see the whole thing I kept a copy.


>The following piece was written by Jim Minton, an aspiring C programmer.
>I convinced him to let me post it to the net.  Happy reading and flames
>to /nev/dull...



>		The Correct Way To Write C if-Statements
>				by
>			    Jim Minton



<<<stuff deleted>>>


>Problem Description

>Let us begin with a brief technical description.  The C language has 
>been designed so that there are several thousand possible ways to 
>write any simple if-statement.  This allows great flexibility and 
>insures that no two programmers anywhere in the universe will ever 
>write an if-statement that looks like any other.  As can quickly be 
>seen, however, this sometimes makes it troublesome to read Code 
>Recorded by Another Programmer (CRAP)[1].  Of course there never has 
>been any problem reading one's own code and this note would not be 
>necessary if all we ever had to read was our own code.  However, 
>(Sigh), it is very often the case that we have to read CRAP[2].

>An important point to remember, and one we hope is strongly 
>reinforced by reading CRAP, is that when other people read our code, 
>it is CRAP to them!  Now here, you see, we have an opportunity to do 
>good-when producing CRAP for other people we can either show our 
>baser meaner natures and try to get even, or we can rise above such 
>pettiness and try to produce something that others will refer to as 
>good CRAP.  We all should, in fact, strive to make others refer to 
>our code as "good CRAP."  This is in fact the origin of the phrase, 
>"There's nothing like a good CRAP," which should, and probably will, 
>become the motto of our Department.


<<<more stuff deleted>>>


>NOTES


<<<stuff deleted>>>


>[2] The original acronym was "CWAP" (for Code Written by Another Programmer).  
>    Unfortunately this acronym makes the speaker sound like Porky Pig, as in, 
>    "You Wascally Wabbit."  To avoid having world leading scientists at a large 
>    prestigious laboratory sound like Porky Pig, the acronym was changed to 
>    CRAP.
>-- 
>Mark Boolootian		booloo@llnl.gov		+1 510 423 1948

Of course, he means Elmer Fudd (eh, eh, eh, eh, eh!).

Neal
Newsgroups: comp.lang.c
From: rhorn@csws11.ic.sunysb.edu (Robert Horn)
Subject: Re: DEC VMS VERSION OF C - HOW TO ASSIGN FILE NAME?
Organization: State University of New York at Stony Brook
Date: Fri, 6 Nov 1992 07:21:47 GMT

In article <92310.16240634R33O7@CMUVM.CSV.CMICH.EDU> Robert A Rawlinson <34R33O7@CMUVM.CSV.CMICH.EDU> writes:
>I HAVE A COUPLE OF STUDENTS DOING SOME C PROGRAMING FOR ME. I AM NOT A
>GOOD C PROGRAMER SO I COULD NOT SEEM TO FIND THE ANSWER IN THE MANUALS.
>IN COBOL I CAN CODE A FILE NAME AND THEN WHEN I RUN THE PROGRAM I CAN
>ASSIGN A FILE NAME AND DIRECTORY. MY STUDENTS CODE IN C AND INDICATED THE
>FILE AND DIRECTORY HAVE TO BE HARD CODED. I SUSPECT THERE IS A WAY TO
>USE A NAME THAT I COULD ASSIGN A FILE AND DIRECTORY TO LATER AS IN COBOL.
>COULD SOMEONE POINT ME IN THE CORRECT DIRECTION TO SOLVE THIS?
>THANKS
>BOB
>
In COBOL you're also required to use all capital letters, right? :)

the function fopen in C's standard libraries <stdio.h> takes a string which
specifies the files name and a string which specifies the permisions, as such
  FILE *fopen(char const *fname, char const *perm);

fname can either be hard coded into the program, or can be any string that the
user has types in, or can even be some randomly generated junk if you feel so
inclined. Look up fopen (and fclose while you're at it) in your favorite C
book (which should be K&R 2nd Edition).

Cheers!
Robb

-- 
rhorn@ic.sunysb.edu           Never choose a college because it has a duckpond.
Would you like to touch my wombat?		  Send me hate mail, I love it.
From: kh5856@eehp6 (Kwun-Heng Ho)
Newsgroups: comp.lang.c
Subject: Help needed with non-recursive floodfill
Date: 13 Nov 92 19:43:23 GMT
Organization: University of Illinois at Urbana


   Could anybody out there think up a non-recursive algorithm for floodfill?
Floodfill is defined as a function/procedure which takes x/y coordinates,
new color, and border color and fills the region bounded by the border with
the new color.  I tried the recursive method but I ran out of stack space.
I'm afraid that after using LISP for a year, everything looks recursive to
me.  I can't for the life of me remember the non-recursive algorithm for 
floodfill!  
   Maybe somebody could give me a recursive algorithm which takes less
space that the one I'm using.

void floodfill(int x,y,new,border)
{
   putpixel(x,y,new);
   if ((getpixel(x+1,y) != border) && (getpixel(x+1,y) != new))
      floodfill(x+1,y,new,border);
   if . . . .
   if . . . . 
   if . . . .
}

You get the idea.... 


Thanks alot...

-- 
************************************************
*                Bor-Tyng Lin                  *
*         kh5856@eehp6.cen.uiuc.edu            *
*       "Love bites" - from "Dracula"          *
Newsgroups: comp.lang.c
From: reeves@rocky1 (Malcolm Reeves)
Subject: Re: Fortran to C conversion: Why bother?
Reply-To: reeves@rocky1
Organization: University of Saskatchewan
Date: Wed, 11 Nov 1992 18:11:59 GMT

From article <20849@fritz.filenet.com>, by scotth@felix.filenet.com (Scott Hopson):
> Keywords
> In article <1992Nov9.131601.167@gems.vcu.edu> hleaves@gems.vcu.edu writes:
>>I was wondering why anyone would bother using the f2c (or similar) program to
>>translate fortran code directly into C. All you end up with is C code that
>>exactly mimics the functionality of the original fortran code. Its not as if
>>the translating program rewrites your algorithms to use the parts of C that
>>make C really useful. Its just fortran code expressed in C. What's the point?
>>If you're going to write programs in fortran, use a fortran compiler. If you
>>want to use the features of C, learn C and use a C compiler. Using f2c doesnt
>>give you any of the advantages of designing and writing the original program 
>>in C.

Having tried all three options:

(1) maintain the fortran code and call it from C
(2) use f2c to convert
(3) rewrite the functions in C

I find that (3) is by far the most effective and often the fastest way of
generating useable low maintenance code. (1) works well if the fortran does
little or no I/O ,for example, numerical algorithms etc. (2) generates
C code will all the advantages of fortran! The only situation in which it
is useful is if you don't have a fortran compiler - you can use your C
compiler only.

I would recommend hacking out all standalone fortran routines into a C
callable library and rewriting I/O and user interfaces in C. When time is
available - it never happens but just imagine - convert the fortran routines
to C if you can't live with library calls.

There are a few problems with interfacing C and fortran but for a lot of 
fortran code, learning how interface is a small overhead.

None of this should be taken as a critisism of f2c. It's a great utility
and does exactly what it promises. You could consider turning your
fortran code into a C library with f2c - but I find f2c C very hard to
maintain - much more difficult than the original fortran - but then I'm
old enough to remember fortran before f66.

--
------------------------------------------------------------------------------
Malcolm Reeves, Geological Engineering, University of Saskatchewan, Saskatoon,
SK, S7N 0W0 aka reeves@rocky1.usask.ca aka reeves@dvinci.usask.ca
------------------------------------------------------------------------------
Newsgroups: comp.lang.c
From: vcsc538@sfsuvax1.sfsu.edu (J. Loh)
Subject: C compiler for Vax/VMS?
Originator: vcsc538@sfsuvax1.sfsu.edu
Organization: San Francisco State University
	Does anyone know were I can find a cheap preferably pd/free C
Date: Sat, 14 Nov 1992 02:40:18 GMT


Newsgroups: comp.lang.c
From: niu@prancer.eche.ualberta.ca (Shaohua Niu)
Subject: Two-dimensional Array
Organization: University Of Alberta, Edmonton Canada
X-Newsreader: Tin 1.1 PL3
Date: Fri, 6 Nov 1992 16:33:15 GMT

I am trying to use dynamic memory allocation for two-dimesional
matrices and the code fragment is as follows:

typedef float **MATRIX;

MATRIX calloc_matrix(int row, int col)
{
  int i;
  MATRIX mat;
  mat = calloc(row, sizeof(float *));
  if (mat==NULL) exit(1);
  for (i=0; i<row; i++) {
	mat[i] = calloc(col, sizeof(MATRIX));
	if (mat[i]==NULL) exit(1);
  }
   return mat;
}

when this is called with row=9 and col=9, the fucntion works for the
pointer mat[0] to mat[6], but for mat[7], it exited abnormally to DOS,
with an error message saying memory allocation error, and the DOS
is halted. It seems that memory allocation of mat[i] is in conflict
with the operating system codes resides in the memory. Actually this 
piece of code is quite close to the example in the FAQ. But why does
it not work. I am using Microsoft C/C++ 7.0 under DOS5.0.

Can anybody kindly point out my problem?

Thanx in advance.

--

       |        ------------------------------------------------------------  
  | ---+----    Shaohua Niu           |    
 /     |        Dept. of Chem. Eng.   |  Email: niu@prancer.eche.ualberta.ca  
  -----+-----   Univ. of Alberta      |  Phone: (403) 432-7803 (Home)         
       |        Canada, T6G 2G6       |         (403) 492-2971                
       |        -------------------------------------------------------------
  
Newsgroups: comp.lang.c
From: dfuller@portal.hq.videocart.com (Dave Fuller)
Subject: ANSI C code 
Organization: VideOcart Inc.
X-Newsreader: Tin 1.1 PL3
Date: Thu, 5 Nov 1992 19:20:31 GMT

   Since i have been contributing a fair amount of code lately, and it
hasn't always been in line with the ANSI standard, i will do a better
job of trying to match to the ANSI standard. This will slow down the
corrections traffic, and also make the code more portable.

Someone who gets code that is non-ANSI, however, i feel should be able
to take the code and modify it to the ANSI standard. It is the logic and
flow that anybody is looking for. At least I'm giving an answer to the
problem. 

I'm a bit upset, but who gives a shit. I also don't want to create any
problems for somebody who gets my code and uses it and has ANY problem.

ANSI hello

Dave Fuller
dfuller@portal.hq.videocart.com
From: d90-awe@tukur.nada.kth.se (Assar Westerlund)
Newsgroups: comp.lang.c
Subject: Re: Is this ANSI C?
Date: 8 Nov 92 19:00:25 GMT
Organization: Royal Institute of Technology, Stockholm, Sweden

In article <1dhkrtINNj99@duvel.cs.ubc.ca> hassan@cs.ubc.ca (Moustafa Hassan) writes:

   #include <stdio.h>
   void main(void)
   {
     printf("hello world\n");
   }

   To settle a dispute, would someone please tell me whether the above
   is ANSI C.  I claim that 'main' (according to the pure ANSI standard)
   must return an integer value, but nonetheless, some non-purists claim
   that the above is ANSI.  Please do not respond via email; I want 
   my opponent (8^) to be able to see all the messages.

According to the ISO standard, equivalent to ANSI C:

5.1.2.2.1 Program startup

[ ... ]

It can be defined with no parameters:

int main(void) { /* ... */ }

or with two parameters [ ... ]
Newsgroups: comp.lang.c
From: bandy@netnews.jhuapl.edu (Mike Bandy)
Subject: Re: How to pass a 2-dim array to a procedure!!
Organization: JHU/Applied Physics Laboratory
Date: Thu, 12 Nov 1992 16:48:30 GMT

fahad@cs.pitt.edu (Fahad A Hoymany) writes:

>Could some one tell me how I can write the procedure line for a function
>which accepts a 2-dimensional array without specifying the dimension?

>For example: I would like to be able to do this:

>int procedure (a[][])    /* Is not accepted by the compiler */

>whereas:

>int procedure (a[])  /* for a 1-dimensional array is acceptable */

A 2-d array is really stored as a contiguous array of elements.
Therefore, the compiler has to know how many elements are in the row 
in order to advance from row to row.  Hence, you have to give the
number of columns but the number of rows is optional.  Like:

main()
{
int ary[10][20];
	subr(ary);
}

subr(a)
int a[][20];
{
	x = a[1][0];	/* get zero'th element from first row */
}

There is a way around passing the number of columns by taking advantage
of the linear property of the 2-d array.  Note that this is not 100%
true in all cases since 2-d arrays can also consist of multiple 1-d
arrays, in which case the elements are not contiguous.  But this works 
given the usual array definition like the following.  I suspect that 
lint would complain, too.

main()
{
int ary[10][20];
	subr(ary,20);		/* pass number of columns in the row */
}

subr(a,dim)
int a[], dim;
{
#define GET_A(row,col) a[row*dim+col]
/* then use the macro to get the pseudo 2-d element from the array */
	x = GET_A(1,0);		/* get zero'th element of first row */
}

-- 

	Mike Bandy
	bandy@aplcomm.jhuapl.edu
	Johns Hopkins University / Applied Physics Lab
From: kdq@quest.UUCP (Kevin D. Quitt)
Newsgroups: comp.lang.c
Subject: Re: How to use 'return' in c?
Date: Tue, 10 Nov 92 20:51:53 PST
Reply-To: srhqla!quest!kdq
Organization: Job quest  (805) 251-8210,  So Cal: (800) 400-8210

mccall@mksol.dseg.ti.com (fred j mccall 575-3539) writes:

> In <gm5XTB3w165w@quest.UUCP> kdq@quest.UUCP (Kevin D. Quitt) writes:
> >    On the other hand, since C does not truly support the boolean type,
> >I consider it misleading to assign a numeric value to a boolean.  I
> >define TRUE as (1==1) because the result of this is a boolean - the
> >fact that it is represented by a numerical value is misleading.
> 
> No, the result of this is *1*.  If it is anything else, your compiler
> is seriously broken.

    No, the result is *represented* by a 1.  "1" is not a boolean value.
TRUE is a boolean value that requires a numeric definition because of
the limitations of the language.  Other languages have booleans and do
not allow assigning numeric values to booleans.  (On the other hand,
most of *those* languages are otherwise so broken as not warrant their
use.)


 _
Kevin D. Quitt      96.37% of all statistics are made up.     srhqla!quest!kdq
Newsgroups: comp.lang.c
From: darcy@druid.uucp (D'Arcy J.M. Cain)
Subject: Re: How to use 'return' in c?
Date: Sat, 7 Nov 1992 12:21:26 GMT
Organization: D'Arcy Cain Consulting

allebrandi@ipact.com writes:
>The best thing to do is to use manifest constants to implicitly document
>the value you are returning. For example, return TRUE or FALSE not 1 or
>0 for a boolean function return.

Whenever I see TRUE and FALSE in code I am maintaining I remove the
#defines.  If they are defined, they should never be anything but
TRUE = 1 and FALSE = 0.  Anything else is confusing and misleading.
Given this why force the maintainer to go searching for the definitions
to make sure that they are what they should never be anything but?
This isn't as bad as #defining SEVEN as 7 but it is in the same category
I think.

-- 
D'Arcy J.M. Cain (darcy@druid.com)  |
D'Arcy Cain Consulting              |   There's no government
Toronto, Ontario, Canada            |   like no government!
+1 416 424 2871          DoD#0082   |
From: ps@cs.strath.ac.uk (Paul Shaw)
Newsgroups: comp.lang.c
Subject: Re: To Recurse or NOT to recurse?
Date: 11 Nov 92 10:17:02 GMT
Organization: Comp. Sci. Dept., Strathclyde Univ., Glasgow, Scotland.

In article <4223@litchi.bbn.com> cbarber@bbn.com (Chris Barber) writes:
>In article <1992Nov6.185136.8055@netcom.com> sjs@netcom.com 
>(Stephen Schow) writes:
>
>Recursion should usually be avoided in C for reasons of efficiency.  A
>recursive linked-list traversal will require much greater overhead both for
>CPU cycles (because of the instructions needed to make function calls) and
>storage space (because of the use of the stack) than a while-loop traversal.
>

I'd just like to give a view which most people seem to disagree with here.
I find that it is _always_ better to use recursion for traversing
recursive data structures (at least in the first development cycle).
   I used to do all my traversals iteratively, but it was so yukky to delete
items etc. from a list without maintaining pointers to previous elements
or pointers to the previous elements `next' field (which is a bit better).
Either way, I found the code hard to read and I made errors quite a bit.
I thought, what is all this complexity buying me?  Maybe a 30%-40% increase
in speed for those routines at the very best.  Stack space being saved?
Well, none of my lists are too long (30 elements), so that's maybe half a
kilobyte.  It didn't seem to me to be worth it for the debugging time it
was costing me, so I started making my traverals of recursive data
structures recursive (makes sense if you think about it :->).

>However, recursion can be appropriate if it greatly simplifies the code and
>will not need to recurse very many levels, thus minimizing the cost of the
>overhead.

   IMHO, if you (people in general, not Christopher Barber) find that
recursion is using tons of stack space and loads of time, your lists are
too long.  You should be using some other data structure (tree/hash table etc.)
which makes the _complexity_ of your search algorithm less (e.g. O(ln n)
instead of O(n)), not scraping around trying to increase the speed of your
code by 30% by using hard-to-read constructs.
   I don't want flamed here by people saying to me `well that extra 30% speed
is important to me'.  It may well be, but (and I'm sure many people
agree with me on this at least), you should always leave optimization
until you can properly profile your code and see what is taking the
time.  If you need the speed, then that is the time to optimize.
Of course, some people may not consider this an optimization.  I do, since
it makes the code run faster/smaller by trading off readability etc.

>This advice does not apply to code written in Lisp and other languages that
>optimize tail-recursion.

Many C compilers will optimize tail recursion to an iterative loop.

>-- 
>Christopher Barber
>(cbarber@bbn.com)

Paul Shaw,
Dept of Computer Science,
University of Strathclyde,
Glasgow.
Newsgroups: comp.lang.c
From: dfuller@portal.hq.videocart.com (Dave Fuller)
Subject: Re: getch
Organization: VideOcart Inc.
X-Newsreader: Tin 1.1 PL3
Date: Fri, 13 Nov 1992 16:27:27 GMT

c60c-2gf@web-2a.berkeley.edu writes:
: 
: At home, I run a version of Turbo C on my IBM.  There is a library function
: with a prototype in conio.h called getch (and getche).  Is there an 
: equivalent of this function on standard Unix systems.  I'm on a Sun, I 
: believe (not a Sparc station though).  This question may be really
: obvious, but I am not quite sure how all the specifics with input/output
: work on the system (i.e. x-window control etc.) and I can't quite seem
: to find getch.  The man page goes on and on abou'curses,' but I am still
: pretty lost.  Any help would be appreciated (in email, please).  Thanks
: 
: -David Simpson

The getch() call is part of the curses package. What you are looking for
is probably getc() getchar() or fgetc(). the g??? are macros and fgetc()
is a function. getchar is just getc(stdin). getc and fgetc both take 
a file pointer (stdin in your case).

the problem with these is that they do not get anything from stdio until
the ENTER key
is hit (or EOL or EOF, or whatever the delimiter is). What this means
is that you get no immediate response to a key hit, AND it is echoed to 
the stdout. so to get 1 key , they may type 100 keys, see them all, and
then alert the program that it has a key in the buffer AFTER all input
is done and ENTER is pressed. This probably is not what you want.  

Curses lessons cannot be given here, but here is a quick layout that 
should help you.

in the main() start out by 
   initscr(); - start curses.
   cbreak(); - this makes each key available immediately instead of waiting
               for a delimiter to occur (like getc(), getchar() and fgetc())
               without this, keyboard info is buffered to tty.
   noecho(); - use this if you don't want the keypresses echoed to screen.
   keypad(stdscr, TRUE); turns the function keys, keypad translation on
   
   this should do it.

   now calls to getch() will return a keypress without delay, but any key
   hit will NOT be echoed to screen, thanks to noecho(). If you want to 
   echo, take this out.

   at the end to shut off curses just use 
   
   endwin()

on a Sun using cc you need to add libraries curses and termlib.
i.e:  cc myprog.c -omyprog -lcurses -ltermlib

don't forget to #include <curses.h> in all files that use getch();

if you forget to use initscr() the program will coredump on you.

Dave Fuller
dfuller@portal.hq.videocart.com


Newsgroups: comp.lang.c
From: dkeisen@leland.Stanford.EDU (Dave Eisen)
Subject: Re: Hows this for odd
Organization: Sequoia Peripherals, Inc.
Date: Thu, 12 Nov 92 16:50:00 GMT

In article <1992Nov12.094905.20522@thunder.mcrcim.mcgill.edu> mouse@thunder.mcrcim.mcgill.edu (der Mouse) writes:
>	char *s;
>	...
>	 for (i=0;i<strlen(s);i++)
>	  { ...code that doesn't modify the string s points to...
>	  }
>

I have a colleague that does this all the time and it drives me
up a wall, but really, how bad is it? It is at least as easy to 
understand as assigning strlen (s) to a temp and looping till i 
hits that temp and it wastes, oh, about 8 micro-seconds. Big deal.



-- 
Dave Eisen                               Sequoia Peripherals: (415) 967-5644
dkeisen@leland.Stanford.EDU              Home:                (415) 321-5154
       There's something in my library to offend everybody. 
          --- Washington Coalition Against Censorship
Newsgroups: comp.lang.c