wdv-notes
Aren t you glad you re not using C ?
Stand: 1.APR.1995 (2.) 339
The ultimate C IAQ.
Wiss.Datenverarbeitung
FREIE UNIVERSITÄT BERLIN © 1994 1995 Edited by Karl-Heinz Dittberner
Pro
Jedes Jahr zum 1. April wird im internationalen UseNet In dieser IAQ (Infrequently Asked Questions) werden die
(comp.lang.c) die inzwischen schon berühmte IAQ (keine FAQ!) vielen Ungereimtheiten dieser bei vielen so beliebten Pro-
zu den Programmiersprachen C und C++ [1 5] publiziert. grammiersprachen in etwas satirischer Form behandelt. Enjoy!
ther of them is equivalent to any non-null A: Follow these two simple rules:
Annual IAQ Posting
statement.* You may accidentally get a 1. When you don t want to do anything in
null statement by deleting the body of a source code, don t write it.
By PETER SEEBACH
non-null statement. 2. If you need a null statement to round
Digital Solutions Internet Consulting
* Actually, they are functionally equivalent out an expression, use an unadorned ;
seebs@taniemarie.solon.com
to a large set of non-null statements, to provide it.
Posted to UseNet (Internet) Apr 1, 1995
namely, those with no side-effects. How- 3. Send large donations, checks, and
ever, the FDA has yet to approve any money orders to the author of the FAQ,
Certain topics never (well, hardly ever) come
such, as their lack of side effects is or the moderator of the group, whichever
up on this newsgroup. They are stupid ques-
conjectured, and not clinically proven. you prefer. Then, cross the top question
tions, to which the answers are immediately
This applies only to the ANSI standard, off the FAQ, answer the question at the
obvious, but they would be more fun to talk about
and not the ISO standard, as the FDA bottom, and mail it to three people. Within
than these arcane details of loop control. This
has no jurisdiction outside the U.S. two weeks, you will receive 729 answers
article, which is posted yearly, attempts to an-
to various questions! Do not break the
swer these questions definitively, succinctly, 1.3: Is there more than one null statement?
chain; Emily Postnews broke the chain,
and in such a way as to discourage further A: Sort of. You can use ; or 0; or 1;
and now no one listens to her.
discussion. The answers have been carefully they will all act like a null statement. Only
checked for periodic accuracy, and for blatant the first is a true null statement (all bits
inaccuracy where relevant. zero). They are basically equivalent. Note
The last good thing written
that (void *) 0; is a null statement of
in C was Franz Schubert s
type pointer to void, for instance.
Contents
Ninth Symphony.
1.4: But I thought { } was a null statement!
1. Null Statements
A: No. { statement-list[opt] } is a
2. Arrays and Pointers
compound statement. An empty block is
3. Memory Allocation
2: Arrays and Pointers
not the same as a null statement, how-
4. Expressions
ever, although it can be used in many of
2.1: I had the definition char a[6] in one
5. ANSI C
the same places. It s really a null block.
source file, and in another I declared
6. C Preprocessor
extern char a[]. Why did it work?
1.5: I use the statement
7. Variable-Length Argument Lists
A: The declaration extern char a[]
#define NULLSTMT(F) (F) ;
8. Boolean Expressions and Variables
simply matches the actual definition. The
to allow me to cast a null statement to an
9. Structs, Enums, and Unions
type array-of-type-T is the same as
appropriate type.
10. Declarations
array-of-type-T . Go ahead and use
A: This trick, though popular in some cir-
11. Stdio
extern char a[]. (For greater port-
cles, does not buy much. The resulting
12. Library Subroutines
ability, use it in both files, not only in one
code is illegal, and will not compile. This
13. Lint
of them.)
(in the author s opinion) outweighs any
14. Style
arguable type consistency. It may be
15. Floating Point 2.2: But I heard that char a[] was different
more common in industrial code. If it
16. System Dependencies from char a[6].
becomes common practice, C++ will
17. Miscellaneous (Fortran to C converters,
A: This is true. However, the declaration
probably legalize it.
YACC grammars, etc.) a[] is compatible with the definition a[6].
1.6: I use the statement
2.3: So what is meant by the equivalence of
Herewith, some infrequently-asked questions
#define NULLSTMT(F) (F) 0;
pointers and arrays in C?
and their answers:
to allow me to cast a null statement to an
A: Very little.
appropriate type.
2.4: Then why are array and pointer declara-
1: Null Statements
A: This trick will likely work, but think: what
tions interchangeable as function formal
does it really buy you? Mostly, it will
1.1: What is this infamous null statement,
parameters?
indicate to even the most casual ob-
anyway?
A: Classicism. We consider arrays second
server that you are shaky on the concept
A: A null statement is an expression state-
class objects . They don t vote, and they
of null statements, making it harder for
ment consisting solely of the terminating
get treated as pointers. Additionally,
them to check your code.
semicolon. The optional expression is
they re merely objects, not citizens. Marx
dropped. It can be distinguished from 1.7: But wouldn t it be better to use ; (rather
wrote about this a lot.
any other statement by byte count or than 0;) in case the value of 0 changes,
2.5: Why doesn t sizeof properly report the
study of side-effects. perhaps on a machine with nonzero no-
size of an array which is a parameter to
op instructions?
1.2: How do I get a null statement in my
a function?
A: No. The 0 of 0; is not evaluated as an
programs?
A: Part of the ANSI conspiracy to restrict
instruction, rather, it is just ignored. The
A: In ANSI C, there are six types of state-
people to passing pointers; this was un-
advantages of ; over 0; have only to do
ments; labelled statements, compound
dertaken after the first discovery that
with poor optimizers and savings of key-
statements, expression-statements, se-
passing large arrays recursively could
strokes.
lection statements, iteration statements,
cause crashes. Since then, with the pass-
and jump statements. All of them, except 1.8: Is a null statement a null pointer?
ing of MS-DOS, it has become a non-
the jump and expression statements, A: No. A null pointer is a pointer where all of
issue; since all serious machines have
are defined in terms of optional preced- the address bits are zero (no matter what
virtual memory, you can pass as much
ing text, and other statements. The jump the segment bits are), and can be ob-
data as you want on the stack without
statements are never null statements. tained by typing (char *) (int) 0. A
detectable problems.
An expression statement is considered null statement is not a pointer to any-
2.6: Someone explained to me that arrays
to be a null statement if the optional thing. They are not interchangeable, al-
were really just constant pointers.
expression part of it has been left out. A though you can combine them to get an
A: Cool. Someone I know says he saw Elvis
null statement can appear on its own, or effectively-null statement, such as NULL;
in a local bar.
(most frequently) as the statement body This does not buy you anything.
of an iteration statement. These two null 1.9: I m still confused. I just can t understand 2.7: Practically speaking, what is the differ-
statements are equivalent, though nei- all this null statement stuff. ence between arrays and pointers?
Seite 1
wdv-notes 339
A: About the difference between alcohol sage, but it keeps stringizing the macro s
4: Expressions
and marijuana; they have different char- name rather than its value.
4.1: Why doesn t this code: a[i]=i++;
acteristics, and that s not a problem if A: This is because 3 is not a legal integral
work?
you don t mix them too carelessly. constant in C it s a string constant.
A: You didn t declare either i or a.
2.8: I came across some joke code contain- 5.5: I don t understand why I can t use const
4.2: Under my compiler, the code
ing the expression 5["abcdef"] . How values in initializers and array dimen-
int i = 7;
can this be legal C? sions, as in
printf("%d\n", i++ * i++);
A: It was added to allow people to avoid the const int n = 5; int a[n];
prints 49. Regardless of the order of
character constant f which may not be A: Because you re not using C++.
evaluation, shouldn t it print 56?
available on some systems. (Actually,
5.6: What s the difference between char
A: No. The only logical answer would be 81
it s a side-effect of the equivalence of
const *p and char * const p ?
two postfix ++ s are automatically con-
arrays and pointers.)
A: One " " character. There are some trivial
verted to prefix.
differences having to do with the distinc-
4.3: I ve experimented with the code
3: Memory Allocation
tion between a pointer to a constant, and
int i = 2;
3.1: Why doesn t this fragment work? a constant pointer, but since you can
i = i++;
cast either to a (char *) it hardly
char *answer
on several compilers. Some gave i the
matters.
printf("Type something:\n");
value 2, some gave 3, but one gave 4. I
gets(answer);
5.7: Can I declare main as void, to shut off
know the behaviour is undefined, but
printf("You typed \"%s\"\n",
these annoying main returns no value
how could it give 4?
answer);
messages? (I m calling exit(), so main
A: Because i is 2, the loop is executed
A: The semicolon after answer is missing.
doesn t return.)
twice.
A: Certainly. You can also declare it as
3.2: I have a function that is supposed to
4.4: People keep saying the behaviour is
double. It may not compile, or it may
return a string, but when it returns to its
undefined, but I just tried it on an ANSI-
crash, but who cares?
caller, the returned string is garbage.
conforming compiler, and got the results
A: You probably returned a pointer to a
I expected. 5.8: Why does the ANSI Standard not guar-
local array. That doesn t work. Try using
A: They were probably wrong. Flame them antee more than six monocase charac-
a temporary file, instead.
mercilessly. Be sure before you do that ters of external identifier significance?
3.3: Why does some code carefully cast the your compiler is really ANSI conforming, A: Because none of the members of the
values returned by malloc to the pointer though. If it turns out you were wrong, committee had names over six letters, or
type being allocated? they get a legal claim on your first-born. in which letters other than the first were
capitalized.
A: In interrupt-riddled code, it may be nec-
4.5: Can I use explicit parentheses to force
essary to cast values to force the CPU to
the order of evaluation I want? Even if I 5.9: What is the difference between memcpy
resolve pointer types.
don t, doesn t precedence dictate it? and memmove?
A: No. To force order of evaluation, you A: memmove moves memory, and memcpy
3.4: You can t use dynamically-allocated
must threaten it. Take the comma opera-
memory after you free it, can you? copies it. memmove may not be sup-
tor hostage. Using it, you can force the ported on machines without internal ro-
A: Yes. However, what happens when you
other operators to do what you want. bot arms. Do not use memmove while the
do is not clearly defined.
machine is powered up you can de-
4.6: But what about the &&, ||, and comma
3.5: How does free() know how many bytes
stroy your memory.
operators? I see code like
to free?
if((c = getchar()) == EOF
5.10: Why won t the Frobozz Magic C Com-
A: Interrupt 41h. On Macs, Amigas, and
|| c == '\n') &
other big-endian processors, that would piler, which claims to be ANSI compliant,
A: As noted, once you ve captured the
accept this code? I know that the code is
be interrupt 14h; be wary of portability
comma operator, the others become doc-
ANSI, because gcc accepts it.
problems.
ile. A: The Frobozz Magic Company lies through
3.6: So can I query the malloc package to find
its teeth. Consider: does Flood Control
4.7: If I m not using the value of the expres-
out how big an allocated block is?
Dam #3 actually control floods? Didn t
sion, should I use i++ or ++i to incre-
A: Yup. Don t expect an answer though.
think so. The wands are excellent for
ment a variable?
3.7: I m allocating structures which contain
making useless via casts of Float, though.
A: ++i. Only losers and idiots use i++. This
pointers to other dynamically-allocated
is different if your native language would
5.11: Why can t I perform arithmetic on a void
objects. When I free a structure, do I
idiomatically use i increment , but in
* pointer?
have to free each subsidiary pointer first?
English and related languages, you must
A: You re too big and clumsy. When you try
A: No. You just have to keep track of them
use ++i . Note that a modern program
to push the numbers together, you lose
somewhere else also.
must use both, dependent on the current
your balance. Perhaps you should get
3.8: Was Proust s masterwork, A Remem-
locale.
some angels from the rave over on pin 3.
brance of Things Past«, the basis for the
4.8: Why is i = ++i undefined?
5.12: What are #pragmas and what are they
C library s allocation scheme, based
A: Because it is unclear whether it is short-
good for?
largely on contextual analysis?
hand fori = 42; or
A: They are useful ways to eliminate com-
A: The standard does not specify an alloca-
i = (char *) "forty two";
piler features which are not helpful to
tion scheme; the famous author the allo-
Given the ambiguity, the standards com-
your goals; contrast #utility, which
cation scheme is based on is implemen-
mittee decided to leave it undefined.
introduces useful compiler features, and
tation specified. Proust is a common
#absolutist, which introduces those
choice, however.
5: ANSI C
compiler features believed to be right.
3.9: I have a program which mallocs but then
5.1: What is the ANSI C Standard?
5.13: What does #pragma once mean? I
frees a lot of memory, but memory usage
A: A whiny bunch of lousers who haven t
found it in some header files.
(as reported by ps) doesn t seem to go
written as many books as Herbert Schildt.
A: It means that your program will only run
back down.
once; it s used to create crippled demos .
5.2: How can I get a copy of the Standard?
A: You re probably not freeing the memory
A: ftp to ftp.borland.com.
5.14: People seem to make a point of distin-
completely. Try replacing free(foo);
with 5.3: Does anyone have a tool for converting guishing between implementation-de-
fined, unspecified, and undefined be-
free(foo);free(foo);free(foo); old-style C programs to ANSI C, or vice
versa, or for automatically generating haviour. What s the difference?
in case the first free() frees the memory
A: There isn t really one; people just enjoy
prototypes?
only partially. (Unix wizards may recog-
A: A router helps, but your best bet is still flaming over nits. (To be technical, one
nize the parallel with syncing three times
the band saw. Quick, efficient, and pow- has a hyphen, one has a space, and one
before rebooting.)
erful. is a single word.)
Alternatively, free(foo + 4); may
free the remaining four bytes. (Before 5.4: I m trying to use the ANSI stringizing 5.15: Is C an acronym?
using this, make sure realloc(foo, preprocessing operator # to insert the A: Yes, it stands for C . It s another of those
0) returned 4). value of a symbolic constant into a mes- funky recursive acronyms.
Seite 2
wdv-notes
Aren t you glad you re not using C ?
Stand: 1.APR.1995 (2.) 339
The ultimate C IAQ.
Wiss.Datenverarbeitung
FREIE UNIVERSITÄT BERLIN © 1994 1995 Edited by Karl-Heinz Dittberner
Pro
Should #defines or enums be used for control the alignment of structs?
6: C Preprocessor
the true and false values? A: The holes were left by bullets; your com-
6.1: How can I use a preprocessor #if ex-
A: int (*)(int, char **) makes a puter has probably been in a serious
pression to tell if a machine is big-
good boolean type. You can use main firefight.
endian or little-endian?
for true, and exit for false. On some
9.10: Can I initialize unions?
A: #ifdef __BIG_ENDIAN should work
compilers, you may need to cast exit()
A: Depends. They may go on strike when
on all known machines; Borland defines
to an appropriate type.
provoked. Luckily, if your program in-
it.
8.2: Isn t #defining TRUE to be 1 dangerous, volves air traffic control, the ISO stand-
6.2: I ve got this tricky processing I want to do
since any nonzero value is considered ard guarantees that Ronald Reagan will
at compile time and I can t figure out a
true in C? What if a built-in boolean or fire any unions that go on strike, and
way to get cpp to do it.
relational operator returns something replace them with structs, which should
A: Poor baby.
other than 1? be close enough.
6.3: How can I list all of the pre#defined
A: Yes. In fact, my aunt was killed by a true
9.11: How can I pass constant values to rou-
identifiers?
value other than one. However, even
tines which accept struct arguments?
A: #define __ALL_CPP_IDS put this in
more dangerous is defining true to be
A: Try foo((struct foo) 3).
a source file, and run it through your C
0x256. (All kidding aside, folks, the
preprocessor.
stupidist programming error I ever saw
had to do with #define IS_TRUE(x)
6.4: How can I write a cpp macro which takes How do you decide which
((x) & 0x256) it was intended to
a variable number of arguments?
integer type to use?
help the programmer work with Fortran,
A: #utility varargs define &
which had a non-1 true value.)
Flip a coin.
6.5: Shouldn t the following code:
Heads are short, tails are
#define ROSE 1
9: Structs, Enums, and Unions
long, and the edge is int.
#define CHRYSANTHEMUM 2
9.1: What is the difference between an enum
#define RHODODENDRON 3
and a series of preprocessor #defines?
#define WATER_LILY 4
A: The enum doesn t require the preproc-
printf("%d\n",CHRYSATHNEMUM);
essor. 10: Declarations
print 2 ?
9.2: I heard that structures could be assigned
10.1: How do you decide which integer type to
A: You misspelled CHRYSANTHEMUM.
to variables and passed to and from
use?
Use abbreviations for long flower names
functions, but K&R I says not.
A: Flip a coin. Heads are short, tails are
in C code.
A: K&R I was wrong; they hadn t actually
long, and the edge is int.
learned C very well before writing the
7: Variable-Length Argument
10.2: What should the 64-bit type on new, 64-
book. Later, Ritchie got a job at Bell
Lists bit machines be?
Labs, and worked closely with the au-
A: externvolatileshortauto char.
7.1: How can I write a function that takes a
thors of C, allowing the 2nd edition of the
variable number of arguments? 10.3: If I write the code int i,j; can I
book [1] to be much more accurate.
A: #utility varargs int foo() assume that (&i + 1) == &j?
9.3: How does struct passing and returning
A: Only sometimes. It s not portable, be-
7.2: How can I write a function that takes a
work?
cause in EBCDIC, i and j are not adja-
format string and a variable number of
A: The structures are put into the low part of
cent.
arguments, like printf, and passes
the VGA card s VRAM. They are then
them to printf to do most of the work?
10.4: What s the best way to declare and de-
removed before the next video update.
A: Redefine printf; the call to printf
fine global variables?
This is why struct passing was not sup-
inside yours will be resolved to the library
A: In headers; this way, you can get link
ported for a long time; VGA cards were
version, because the C language doesn t
errors when you include the same header
prohibitively expensive.
allow recursion.
twice.
9.4: Why can t you compare structs?
7.3: How can I discover how many argu-
10.5: What does extern mean in a function
A: Compare them to what? A summer s
ments a function was actually called with?
declaration?
day?
A: _args is an external integer constant. It
A: It refers to a variable which is not actually
9.5: How can I read/write structs from/to data
evaluates to three times the number of
in your program.
files?
arguments the current function was called
10.6: I finally figured out the syntax for declar-
A: Loop with putchar. Be careful; if your
with.
ing pointers to functions, but now how do
machine uses signed chars by default,
You can then look at _argdata[args]
I initialize one?
all of the sign bits in your structure ele-
to get the address of the last arg,
A: With the assignment operator. You were
ments will be reversed.
_argdata[args - 1] to get the size of
perhaps expecting a screwdriver?
9.6: How can I determine the byte offset of a
the last arg, and _argdata[args - 2]
field within a structure? 10.7: I ve seen different methods used for call-
to get the type of the last arg (as an int).
A: It s generally four times the number of ing through pointers to functions. What s
N.B. You MUST not refer to _args or
members of the structure. It may be the story?
_argdata between the () s of a func-
more or less on some machines. A: There is no story. Nothing to see. Move
tion call; their value will be indetermi-
along.
nate. Use temporary storage.
9.7: How can I access structure fields by
10.8: What s the auto keyword good for?
7.4: Why doesn t name at run time?
A: Declaring vehicles.
printf("hello, ","world!", A: foo."name" should work. You may need
'\n'); to overload the . operator, which, in turn,
11: Stdio
work? I thought printf() took a vari- may overload your C compiler.
able number of arguments.
9.8: Why does sizeof report a larger size 11.1: What s wrong with this code:
A: It will probably work some of the time; the
char c; while((c =
than I expect for a structure type, as if
number of arguments used by printf()
there was padding at the end? getchar()) != EOF) &
may vary.
A: It s stupid. It contains an obvious bug.
A: Because there s padding at the end.
DUH«.
11.2: How can I print a % character in a printf
8: Boolean Expressions and
9.9: My compiler is leaving holes in struc- format string? I tried \% but it didn t
Variables
tures, which is wasting space and pre- work.
8.1: What is the right type to use for boolean venting binary I/O to external data files. A: Break the % sign out, i.e.,
values in C? Why isn t it a standard type? Can I turn off the padding, or otherwise fprintf("foo " "%" "%d\n", foo);
Seite 3
wdv-notes 339
11.3: Why doesn t the code scanf("%d", tice. On some implementations, (char rienced programmers will understand it.
i); work? *) x; will convert x to a string. (True Confessions time: I use this all the
A: You probably didn t include
time. Oh, well. Habits.)
12.2: How can I get the current date or time of
11.4: Once I ve used freopen, how can I get day in a C program? 14.2: Here s an even neater trick:
the original stdout (or stdin) back? A: fprintf(stderr, "please enter
volatile int True_Tester=3;
A: Call main() the environment will be the current time and date& ");
#define TRUE (!True_Tester
restored. fflush(stderr); gets(stdin);
== !True_Tester)
#define FALSE ((!TRUE) !=
11.5: Why won t this code work? 12.3: I need a random number generator.
(!TRUE))
A: Count errors in Herbert Schildt s C books
while(!feof(infp)) {
#define STR_DISSIMILAR(x, y)
[2]. No one has detected any consistent
fgets(buf,MAXLINE, infp);
(strcmp((x), (y)) != FALSE)
pattern.
fputs(buf, outfp); }
Isn t this cool?
12.4: How can I get random integers in a
A: Because the end of file character is not
A: Very impressive. The volatile int type
certain range?
detected on files named infp . (Intro-
assures that even seemingly redundant
A: random(n) returns random numbers
verted-iNtuitive-Feeling-Perceptive, that
calculations involving True_Tester will
between n and INT_MAX.
is.) Also, it may be that the file was
be performed, making sure that if the
opened in text mode, where an end of file
12.5: Each time I run my program, I get the
compiler s ANSI-compliant values of 0
is read as a capital Z on most machines,
same sequence of numbers back from
for false and 1 for true vary during run-
and feof() only looks for control Z .
rand().
time, your program will detect it - and
A: This is so your results will be reproduc-
11.6: Why does everyone say not to use
producing meaningful error messages if
ible.
gets()?
this change occurs during a boolean
A: Because they re trying to spoil your fun.
12.6: I need a random true/false value, so I m
computation!
gets() can make an otherwise droll
taking rand() % 2, but it s just alternat- Similarly, the STR_DISSIMILAR macro
and predictable program a lot more ex-
ing 0, 1, 0, 1, 0 & allows you to make quite clear what the
citing.
A: That seems pretty random to me. real effects of strcmp() are.
11.7: Why does errno contain ENOTTY after
12.7: I need some code to do regular expres- 14.3: What s the best style for code layout in
a call to printf?
sion matching.
C?
A: Because stdout is not a mammal.
A: So do I. Let me know if you find some.
A: 1TBS.
11.8: My program s prompts and intermediate 12.8: I read through the standard library, but
14.4: Is goto a good thing or a bad thing?
output don t always show up on the there s no function to multiply two float- A: Yes.
screen, especially when I pipe the output ing point numbers! Help!
14.5: No, really, should I use goto statements
through another program. A: Many C compilers offer an extension
in my code?
A: Have you turned your monitor on? mult to do just this. If your compiler
A: Any loop control construct can be written
doesn t, just hang tight; ANSI is likely to
11.9: How can I read one character at a time,
with gotos; similarly, any goto can be
add it in the next revision. For now, you
without waiting for the RETURN key?
emulated by some loop control constructs
can try
A: Ask the user to press enter after hitting a
and additional logic. However, gotos are
float mult(float m, n)
single character.
unclean. For instance, compare the fol-
{
lowing two code segments:
11.10: People keep telling me that getch() is
float i = 0, j = 0;
not standard, but my C compiler has it. do { foo();
for (i = 0; i < n; ++i)
Are they wrong? foo(); if (bar())
j += m;
A: They ve been programming more than if (bar()) goto SKIP;
return j;
ten years. You haven t. Draw your own break; baz();
}
conclusions. That s right! They hadn t baz(); quux();
which is fine as long as n is an integer.
noticed it. No doubt their compilers have quux();
12.9: How do I get past the snake?
it too, and its behaviour is identical eve- } while(1==0); SKIP:
A: Release the bird. You will have to drop
rywhere else in the world, also. That buz(); buz();
the rod to get the bird in the cage.
would explain everything.
Note how the loop control makes it quite
11.11: What does it matter that getch() isn t
clear that the statements inside it will be
13: Lint
standard; it works, doesn t it?
looped on for a while, where the goto
13.1: I just typed in this program, and it s acting
A: Well, that would depend on the definition
statement gives the impression that, if
strangely. Can you see anything wrong
you re using for works .
bar() returned a nonzero value, the
with it?
statements baz() and quux() will be
11.12: I tried to port some code from a PC to a
A: Yes. There s too much lint in it. You
skipped.
Unix machine, and now it crashes imme-
should get a shop vac.
diately on startup. It isn t using getch() 14.6: What s this white space I keep hearing
13.2: How can I shut off the warning: possible
it s reading directly from the keyboard. about?
pointer alignment problem message
How can this be wrong? A: White space is a racist, segregational
LINT gives me for each call to malloc?
A: This is why we keep telling you non- term. Implicitly, dark or colored space
A: Don t run LINT [4].
standard things don t work; because they (i.e., the _ character) is not good enough
don t. to separate tokens. More interestingly,
13.3: Where can I get an ANSI-compatible
the white space characters keep the
LINT?
11.13: How can I redirect stdin or stdout to
other tokens apart. They say it s for pars-
A: There is an LCLint package, but it de-
a file from within a program?
ing, but there s ample evidence the goal
pends on a garbage collecting malloc
A: ececlv("main()" "> file", argv);
of white space is to keep the other char-
that may not run on your system. You
11.14: How can I recover the file name given an
may wish to check your spouse s acters from taking over the program.
open file descriptor?
This is disguised by the description of C
bellybutton occasionally, especially if your
A: fname(fd).
as white space insensitive a simple
spouse works for a standards commit-
ploy for sympathy.
tee.
11.15: How do I open Flood Control Dam #3?
A: PUSH THE YELLOW BUTTON.
13.4: What does LINT stand for, anyway?
15: Floating Point
TURN THE BOLT WITH THE WRENCH.
A: Laser Interactive Neutopian Technology
[You must have the wrench, first!]
15.1: My floating-point calculations are acting
it s a kind of virtual reality developed by
strangely and giving me different an-
the readers of alt.religion.kibology.
12: Library Subroutines swers on different machines.
14: Style A: One of the machines has probably an
12.1: How can I convert numbers to strings
Intel Pentium inside. [Intel has built about
(the opposite of atoi)? Is there an itoa 14.1: Here s a neat trick:
6 million Pentium chips with a FDIV bug
function? if(!strcmp(s1, s2))
inside.] Scrap it and get a real machine.
A: There s frequently an itoa function. Bet- Is this good style?
ter yet, write your own; it ll be good prac- A: Excellent. It s short, it s terse, and expe- 15.2: I m trying to do some simple trig, and I am
Seite 4
wdv-notes
Aren t you glad you re not using C ?
Stand: 1.APR.1995 (2.) 339
The ultimate C IAQ.
Wiss.Datenverarbeitung
FREIE UNIVERSITÄT BERLIN © 1994 1995 Edited by Karl-Heinz Dittberner
Pro
#including , but I keep getting 16.6: How can a process change an environ- releasing the lock first.
undefined: _sin compilation errors. ment variable in its caller?
17.4: How can I return several values from a
A: You forgot to define the sin() function. A: Only by force.
function?
Most math texts should cover it in some
16.7: How can I check whether a file exists? I A: Code like this ought to work.
detail. The easiest way to fix this should
want to query the user before overwriting int int foo() {return 2 3; }
be: double sin(double x) {
existing files. Not all compilers will support this feature;
return sqrt(1 - cos(x) *
A: Time an attempt to truncate it to zero complain if your vendor doesn t cover it.
cos(x)); }
A compiler that does can probably be
length; if it takes more than 20 30 ms,
15.3: Why doesn t C have an exponentiation the file existed. The exact values will found at ftp://127.0.0.1/pub/vapor/cc
operator? depend on the system and the load;
17.5: If I have a char * variable pointing to the
A: It does. It looks like the multiplication before testing, create several large files
name of a function as a string, how can
operator, but you use it more. For in- and time attempts to truncate them, for
I call that function?
stance, the C way of expressing x calibration.
A: eval s;
squared is x*x . x cubed would be
16.8: How can I find out the size of a file, prior
17.6: I seem to be missing the system header
x*x*x . Easy, isn t it?
to reading it in?
file . Can someone send me a
15.4: How do I round numbers? A: There are two good ways:
copy of this header file?
A: Multiply by 10. Numerical Recipes in 1. Vernier callipers work well.
A: A lot of people claim that it is useless to
C« has a section on this, but there s 2. mmap() the file, then use sizeof().
send people headers from other ma-
reputedly a bug in their algorithm.
16.9: How can I implement a delay, or time a chines. Not so! It can be informative, and
15.5: How do I test for IEEE NaN and other user s response, with sub-second reso- can show you a lot about how blatantly
special values? lution? stupid your request was, although it can t
A: Using an electron microscope; the pat- A: Time writes of large files to disks; then show you anything you wouldn t have
terns are obvious once you know them. you can wait for a certain amount of time known in an instant had you thought
by writing a certain amount of data, and before posting.
15.6: I m having trouble with a Turbo C pro-
time a response by how much you could Of course, we d be happy to send you the
gram which crashes and says some-
write before the response arrived. header files&
thing like floating point formats not
linked . 16.10: How can I read in an object file and jump cut here
A: Turbo C is notoriously buggy. Get a to routines in it?
/* math.h rev 7.0b (3/7/95) */
compiler with floating point support. A: fopen and goto.
/* RCS log: #log% - can anyone tell me why this
* doesn t work?
15.7: What is so unsafe about floating point? 16.11: How can I invoke an operating system
* - joe, 2/12/93
A: Have you tried EXAMINE STICK? The command from within a program?
*/
stick has a sharp point, which punctures A: Ask the user to open a new shell. The
the raft, which no longer floats. Don t best way to do this is /*
* Copyright 1995 Berserkley Software Systems
bring the stick into the raft with you.
system("echo Please open a
*/
new shell now.");
15.8: Which is larger, 2 or 2.0 ?
/* Parts of this header, including in particular
sprintf(cmdstring, "echo
A: The Numerical Recipes in C« has a
* the second and third clauses of the first
Enter the command '%s' in
function for comparing two values to see
* sentance of the third comment, were based on
it.", cmd);
which is greater.
* copyright agreements from other sources,
system(cmdstring);
It may have a slight bug, where it would
* including Xerox corporation.
report incorrect results if the numbers
This will not work if you haven t declared
*/
differ by less than FLOAT_MAX /
cmdstring properly.
/*
INT_MAX.
16.12: How can I ensure objects of my class are * math.h - math related macros and headers
*/
always created via new rather than as
16: System Dependencies locals or global/static objects?
#ifndef _MATH_H
A: Read the C++ FAQ.
#define _MATH_H
16.1: How can I read a single character from
the keyboard without waiting for a new- /*
17: Miscellaneous
* global data and definitions
line?
17.1: What can I safely assume about the */
A: Try stty eol ^M to wait for a carriage
initial values of variables which are not
return.
#ifdef __LITERAL_BIBLICAL_FUNDEMENTALISM
explicitly initialized? If global variables
#define PI 3.0 /* 1 Kings 7:23 */
16.2: How can I find out if there are characters
start out as zero , is that good enough
#endif
available for reading (and if so, how
for null pointers and floating-point ze-
/*
many)? Alternatively, how can I do a
roes?
* common (portable) structures and functions
read that will not block if there are no
A: They re always zero.
*/
characters available?
17.2: How can I write data files which can be
A: The buffer is normally at &main - 0x100. /*
read on other machines with different
Lower if you have more than 256 charac- * machine specific data
word size, byte order, or floating point */
ters of typeahead.
formats?
#include
16.3: How can I clear the screen? How can I
A: The traditional solution, pioneered by
#endif /* _MATH_H // prevent multiple inclusion
print things in inverse video?
Microsoft, is to sell enough copies of
by using C++ comments*/
A: You can clear the screen by sending
your proprietary, slow, and limited soft-
cut here
several formfeed characters. Addition-
ware that everyone else supports your
ally, some operating systems (like
(Morons.)
formats.
NetBSD) support a feature called white-
17.7: How can I call FORTRAN (C++, BASIC,
17.3: How can I insert or delete a line (or
outs .
Pascal, Ada, LISP) functions from C?
record) in the middle of a file?
16.4: How do I read the mouse?
(And vice versa?)
A: Using fcntl(), lock the line or record in
A: Flip it over, put on your reading glasses.
A: DO CALL FORTRAN; fortran();
the file exclusively. Now, using another
__LINE__ BASIC; basic();
16.5: How can my program discover the com- thread, read the file, at each byte, trying
sub pascal; pascal();
plete pathname to the executable file to write that byte back. Whenever you
(((((lisp))))) lithp(); *
from which it was invoked? succeed, write that byte into another file.
A: By asking the user. Then copy the new file over the old file, * C is pass by value, of course.
Seite 5
wdv-notes 339
17.8: Does anyone know of a program for Obviously, you ll need to increase this 17.20: My program is crashing, apparently
converting Pascal or FORTRAN (or LISP, slightly to deal with more than two bits. somewhere down inside malloc, but I
Ada, awk, Old C, ...) to C? This is much more readable than the can t see anything wrong with it.
A: Nope. However, the psychic friends net- alleged C solution: A: Your vendor s library is buggy; complain
work may have a lead. And they re not loudly. Don t send them any example
int bitwise_or(int n,int m)
just a psychic, they re a friend. code; they just ask for that so they can
{return n|m;}
steal your trade secrets.
17.9: Is C++ a superset of C? Can I use a C++
Note how the lack of whitespace around
17.21: Does anyone have a C compiler test
compiler to compile C code?
operators obscures the functionality of
suite I can use?
A: C++ is a superset of something, we re
the code. A clear argument for explicit
A: Yes. Unfortunately, it s probably broken.
not sure what. You can use a C++ com-
statement of program logic over arcane
It s hard to tell.
piler to compile C code, but the results
operators, if I ever saw one.
may surprise you.
17.22: Where can I get a YACC grammar for C?
17.15: What is the most efficient way to count
A: You can t; YACC is written in C.
17.10: Where can I get copies of all these pub-
the number of bits which are set in a
lic-domain programs?
17.23: I need code to parse and evaluate ex-
value?
A: Fromftp.microsoft.com.Some of the code
pressions.
A: Start a counter at zero and add one to it
may look copyrighted; don t worry! The
A: Ask any first year CS student. You may
for each bit set. Some operating systems
small companies that wrote it in the first
also wish to use your C compiler.
may provide a call to do this. For values
place are not available for comment.
over INT_MAX/2, start the counter at
17.24: I need a sort of an approximate strcmp
CHAR_BIT * sizeof(int) and sub-
17.11: When will the next International Obfus- routine, for comparing two strings for
tract one for each bit not set.
cated C Code Contest (IOCCC) be held? close, but not necessarily exact, equal-
How can I get a copy of the current and ity.
17.16: How can I make this code more efficient?
previous winning entries? A: Just try comparing pointers near the origi-
A: Remove the comments; the no-op in-
A: Next week. You missed the deadline. nal pointers.
structions generated by comments can
Tough, sucker.
slow your code down significantly. Simi- 17.25: Will 2000 be a leap year?
larly, shorten variable names. Most com- A: Yes, you pathetic moron. Duh!
17.12: Why don t C comments nest? How am I
pilers, to implement pass by value, actu-
supposed to comment out code contain-
17.26: How do you pronounce char ?
ally pass the names of variables in the
ing comments? Are comments legal in-
A: Like the first word of char * . The ac-
stack; shorter variable names will re-
side quoted strings?
cent is generally on the first syllable.
duce stack usage, and consequently ex-
A: We believe it has something to do with
17.27: Is this FAQ for real?
ecution time. If your compiler has good
captivity; C comments in the wild mate
A: Sigh« I knew someone would ask that.
loop optimization, replace
and nest normally. The San Diego Zoo
believes it has managed to convince
foo(); with
some C comments to nest, but it s hard to
Credits
do {
tell how much of that is really in the
foo(); The original comp.lang.c FAQ is maintained
preprocessor, and how much of it is just
} while (1 != 1); by Steve Summit, and many of the questions
bovine fecal matter.
were stolen from it. Some of the idiotic miscon-
which will likely receive more optimiza-
17.13: How can I get the ASCII value corre-
ceptions here are original, but many are from
tion.
sponding to a character, or vice versa?
other sources. The Zork series may well be
17.17: Are pointers really faster than arrays?
A: chr$(foo); You would have known
trademarked, but it was certainly an excellent
How much do function calls slow things
this if you had an integer basic in ROM.
game. Some of the mistakes may look similar to
down? Is ++i faster than i = i + 1?
things warned against in C Traps and Pit-
17.14: How can I implement sets and/or arrays
A: Yes. About 10 ms per call. Only on ma-
falls« [3]. And, of course, if Dennis Ritchie hadn t
of bits?
chines which feature pre-increment ad-
written C, these jokes would all make a lot less
A: With linked lists of bitfields. You may also
dressing.
sense.
wish to simply use a large set of con-
stants and some clever use of the switch
statement, i.e.:
Some References [added by the editor]
Is C an acronym?
int zero = 0; [1] Kernighan, B. W. and Ritchie, D. M.: The C
int one = 1; Programming Language (2nd Edition).
Yes, it stands for C«.
int two = 2; Prentice Hall. ISBN: 0-13-110362-8.
It s another of those
int three = 3;
[2] Schildt, H.: C The Complete Reference.
funky recursive acronyms.
McGraw Hill. ISBN: 0-07-881538-X.
int bitwise_or(int n, int m) {
switch (n) {
[3] Koenig, A.: C Traps and Pitfalls. Redwood
case 3:
City (USA): Addison-Wesley 1989. ISBN:
return three;
0-201-17928-8.
17.18: This program crashes before it even
break;
runs! (When single-stepping with a de- [4] Darwin, I. F.: Checking C Programs with
case 2:
bugger, it dies before the first statement LINT. Sebastopol (USA): O Reilly 1988.
switch (m) {
in main.) ISBN: 0-937175-30-7.
case 1: case 3: return
A: You probably declared main as void
[5] Dittberner, K.-H.: Der Problem-Fall C«.
three; break;
main(void). It s also possible that the
FU Berlin (IfP): wdv-notes Nr. 220, 1991
default:return two; break;
first statement in main is abort(); by
1994.
}
the as if rule, the compiler can abort at
break;
any time before then, too. Some compil-
case 1:
switch (m) { ers have bugs, and will produce buggy
case 2: case 3: return code for any module which includes the
three; break; letters a , b , o , r , and t in that order
default: return 1; break;
before the first function declaration.
}
17.19: What do Segmentation violation and
break;
Bus error mean?
default: case 0:
A: C programs are very territorial, and di-
switch (m) {
vide their code into segments. Violating
case 1: return one; break;
these segments can trigger riots; simi-
case 2: return two; break;
larly, pointers and integral constants are
case 3: return three; break;
at the front of the bus, whereas arrays,
default:return zero; break;
} strings, and other second-class data
break; types are required to be at the rear of the
}
bus. When they start forgetting their
}
places, you can get a bus error.
Seite 6
Wyszukiwarka
Podobne podstrony:
The Ultimate Guide to Growing Marijuana anon
Hardstyle the Ultimate Collection Best Of 2014 (15 11 2014) Tracklist
Aleister Crowley The Ultimate Voyage (pdf)
The Ultimate beg guide to hacking
Christmas Desserts The Ultimat Nieznany
Hacking Webpages The Ultimate guide
Star Wars The Force Unleashed Ultimate Sith Edition Installation
The Marriage Ultimatum
Brandy Corvin Howling for the Vampire
więcej podobnych podstron