source: trunk/third/gcc/cpp.info-2 @ 11288

Revision 11288, 41.0 KB checked in by ghudson, 26 years ago (diff)
This commit was generated by cvs2svn to compensate for changes in r11287, which included commits to RCS files with non-trunk default branches.
Line 
1This is Info file cpp.info, produced by Makeinfo version 1.67 from the
2input file cpp.texi.
3
4   This file documents the GNU C Preprocessor.
5
6   Copyright 1987, 1989, 1991, 1992, 1993, 1994, 1995 Free Software
7Foundation, Inc.
8
9   Permission is granted to make and distribute verbatim copies of this
10manual provided the copyright notice and this permission notice are
11preserved on all copies.
12
13   Permission is granted to copy and distribute modified versions of
14this manual under the conditions for verbatim copying, provided also
15that the entire resulting derived work is distributed under the terms
16of a permission notice identical to this one.
17
18   Permission is granted to copy and distribute translations of this
19manual into another language, under the above conditions for modified
20versions.
21
22
23File: cpp.info,  Node: Macro Pitfalls,  Prev: Redefining,  Up: Macros
24
25Pitfalls and Subtleties of Macros
26---------------------------------
27
28   In this section we describe some special rules that apply to macros
29and macro expansion, and point out certain cases in which the rules have
30counterintuitive consequences that you must watch out for.
31
32* Menu:
33
34* Misnesting::        Macros can contain unmatched parentheses.
35* Macro Parentheses:: Why apparently superfluous parentheses
36                         may be necessary to avoid incorrect grouping.
37* Swallow Semicolon:: Macros that look like functions
38                         but expand into compound statements.
39* Side Effects::      Unsafe macros that cause trouble when
40                         arguments contain side effects.
41* Self-Reference::    Macros whose definitions use the macros' own names.
42* Argument Prescan::  Actual arguments are checked for macro calls
43                         before they are substituted.
44* Cascaded Macros::   Macros whose definitions use other macros.
45* Newlines in Args::  Sometimes line numbers get confused.
46
47
48File: cpp.info,  Node: Misnesting,  Next: Macro Parentheses,  Prev: Macro Pitfalls,  Up: Macro Pitfalls
49
50Improperly Nested Constructs
51............................
52
53   Recall that when a macro is called with arguments, the arguments are
54substituted into the macro body and the result is checked, together with
55the rest of the input file, for more macro calls.
56
57   It is possible to piece together a macro call coming partially from
58the macro body and partially from the actual arguments.  For example,
59
60     #define double(x) (2*(x))
61     #define call_with_1(x) x(1)
62
63would expand `call_with_1 (double)' into `(2*(1))'.
64
65   Macro definitions do not have to have balanced parentheses.  By
66writing an unbalanced open parenthesis in a macro body, it is possible
67to create a macro call that begins inside the macro body but ends
68outside of it.  For example,
69
70     #define strange(file) fprintf (file, "%s %d",
71     ...
72     strange(stderr) p, 35)
73
74This bizarre example expands to `fprintf (stderr, "%s %d", p, 35)'!
75
76
77File: cpp.info,  Node: Macro Parentheses,  Next: Swallow Semicolon,  Prev: Misnesting,  Up: Macro Pitfalls
78
79Unintended Grouping of Arithmetic
80.................................
81
82   You may have noticed that in most of the macro definition examples
83shown above, each occurrence of a macro argument name had parentheses
84around it.  In addition, another pair of parentheses usually surround
85the entire macro definition.  Here is why it is best to write macros
86that way.
87
88   Suppose you define a macro as follows,
89
90     #define ceil_div(x, y) (x + y - 1) / y
91
92whose purpose is to divide, rounding up.  (One use for this operation is
93to compute how many `int' objects are needed to hold a certain number
94of `char' objects.)  Then suppose it is used as follows:
95
96     a = ceil_div (b & c, sizeof (int));
97
98This expands into
99
100     a = (b & c + sizeof (int) - 1) / sizeof (int);
101
102which does not do what is intended.  The operator-precedence rules of C
103make it equivalent to this:
104
105     a = (b & (c + sizeof (int) - 1)) / sizeof (int);
106
107But what we want is this:
108
109     a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
110
111Defining the macro as
112
113     #define ceil_div(x, y) ((x) + (y) - 1) / (y)
114
115provides the desired result.
116
117   Unintended grouping can result in another way.  Consider `sizeof
118ceil_div(1, 2)'.  That has the appearance of a C expression that would
119compute the size of the type of `ceil_div (1, 2)', but in fact it means
120something very different.  Here is what it expands to:
121
122     sizeof ((1) + (2) - 1) / (2)
123
124This would take the size of an integer and divide it by two.  The
125precedence rules have put the division outside the `sizeof' when it was
126intended to be inside.
127
128   Parentheses around the entire macro definition can prevent such
129problems.  Here, then, is the recommended way to define `ceil_div':
130
131     #define ceil_div(x, y) (((x) + (y) - 1) / (y))
132
133
134File: cpp.info,  Node: Swallow Semicolon,  Next: Side Effects,  Prev: Macro Parentheses,  Up: Macro Pitfalls
135
136Swallowing the Semicolon
137........................
138
139   Often it is desirable to define a macro that expands into a compound
140statement.  Consider, for example, the following macro, that advances a
141pointer (the argument `p' says where to find it) across whitespace
142characters:
143
144     #define SKIP_SPACES (p, limit)  \
145     { register char *lim = (limit); \
146       while (p != lim) {            \
147         if (*p++ != ' ') {          \
148           p--; break; }}}
149
150Here Backslash-Newline is used to split the macro definition, which must
151be a single line, so that it resembles the way such C code would be
152laid out if not part of a macro definition.
153
154   A call to this macro might be `SKIP_SPACES (p, lim)'.  Strictly
155speaking, the call expands to a compound statement, which is a complete
156statement with no need for a semicolon to end it.  But it looks like a
157function call.  So it minimizes confusion if you can use it like a
158function call, writing a semicolon afterward, as in `SKIP_SPACES (p,
159lim);'
160
161   But this can cause trouble before `else' statements, because the
162semicolon is actually a null statement.  Suppose you write
163
164     if (*p != 0)
165       SKIP_SPACES (p, lim);
166     else ...
167
168The presence of two statements--the compound statement and a null
169statement--in between the `if' condition and the `else' makes invalid C
170code.
171
172   The definition of the macro `SKIP_SPACES' can be altered to solve
173this problem, using a `do ... while' statement.  Here is how:
174
175     #define SKIP_SPACES (p, limit)     \
176     do { register char *lim = (limit); \
177          while (p != lim) {            \
178            if (*p++ != ' ') {          \
179              p--; break; }}}           \
180     while (0)
181
182   Now `SKIP_SPACES (p, lim);' expands into
183
184     do {...} while (0);
185
186which is one statement.
187
188
189File: cpp.info,  Node: Side Effects,  Next: Self-Reference,  Prev: Swallow Semicolon,  Up: Macro Pitfalls
190
191Duplication of Side Effects
192...........................
193
194   Many C programs define a macro `min', for "minimum", like this:
195
196     #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
197
198   When you use this macro with an argument containing a side effect,
199as shown here,
200
201     next = min (x + y, foo (z));
202
203it expands as follows:
204
205     next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
206
207where `x + y' has been substituted for `X' and `foo (z)' for `Y'.
208
209   The function `foo' is used only once in the statement as it appears
210in the program, but the expression `foo (z)' has been substituted twice
211into the macro expansion.  As a result, `foo' might be called two times
212when the statement is executed.  If it has side effects or if it takes
213a long time to compute, the results might not be what you intended.  We
214say that `min' is an "unsafe" macro.
215
216   The best solution to this problem is to define `min' in a way that
217computes the value of `foo (z)' only once.  The C language offers no
218standard way to do this, but it can be done with GNU C extensions as
219follows:
220
221     #define min(X, Y)                     \
222     ({ typeof (X) __x = (X), __y = (Y);   \
223        (__x < __y) ? __x : __y; })
224
225   If you do not wish to use GNU C extensions, the only solution is to
226be careful when *using* the macro `min'.  For example, you can
227calculate the value of `foo (z)', save it in a variable, and use that
228variable in `min':
229
230     #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
231     ...
232     {
233       int tem = foo (z);
234       next = min (x + y, tem);
235     }
236
237(where we assume that `foo' returns type `int').
238
239
240File: cpp.info,  Node: Self-Reference,  Next: Argument Prescan,  Prev: Side Effects,  Up: Macro Pitfalls
241
242Self-Referential Macros
243.......................
244
245   A "self-referential" macro is one whose name appears in its
246definition.  A special feature of ANSI Standard C is that the
247self-reference is not considered a macro call.  It is passed into the
248preprocessor output unchanged.
249
250   Let's consider an example:
251
252     #define foo (4 + foo)
253
254where `foo' is also a variable in your program.
255
256   Following the ordinary rules, each reference to `foo' will expand
257into `(4 + foo)'; then this will be rescanned and will expand into `(4
258+ (4 + foo))'; and so on until it causes a fatal error (memory full) in
259the preprocessor.
260
261   However, the special rule about self-reference cuts this process
262short after one step, at `(4 + foo)'.  Therefore, this macro definition
263has the possibly useful effect of causing the program to add 4 to the
264value of `foo' wherever `foo' is referred to.
265
266   In most cases, it is a bad idea to take advantage of this feature.  A
267person reading the program who sees that `foo' is a variable will not
268expect that it is a macro as well.  The reader will come across the
269identifier `foo' in the program and think its value should be that of
270the variable `foo', whereas in fact the value is four greater.
271
272   The special rule for self-reference applies also to "indirect"
273self-reference.  This is the case where a macro X expands to use a
274macro `y', and the expansion of `y' refers to the macro `x'.  The
275resulting reference to `x' comes indirectly from the expansion of `x',
276so it is a self-reference and is not further expanded.  Thus, after
277
278     #define x (4 + y)
279     #define y (2 * x)
280
281`x' would expand into `(4 + (2 * x))'.  Clear?
282
283   But suppose `y' is used elsewhere, not from the definition of `x'.
284Then the use of `x' in the expansion of `y' is not a self-reference
285because `x' is not "in progress".  So it does expand.  However, the
286expansion of `x' contains a reference to `y', and that is an indirect
287self-reference now because `y' is "in progress".  The result is that
288`y' expands to `(2 * (4 + y))'.
289
290   It is not clear that this behavior would ever be useful, but it is
291specified by the ANSI C standard, so you may need to understand it.
292
293
294File: cpp.info,  Node: Argument Prescan,  Next: Cascaded Macros,  Prev: Self-Reference,  Up: Macro Pitfalls
295
296Separate Expansion of Macro Arguments
297.....................................
298
299   We have explained that the expansion of a macro, including the
300substituted actual arguments, is scanned over again for macro calls to
301be expanded.
302
303   What really happens is more subtle: first each actual argument text
304is scanned separately for macro calls.  Then the results of this are
305substituted into the macro body to produce the macro expansion, and the
306macro expansion is scanned again for macros to expand.
307
308   The result is that the actual arguments are scanned *twice* to expand
309macro calls in them.
310
311   Most of the time, this has no effect.  If the actual argument
312contained any macro calls, they are expanded during the first scan.
313The result therefore contains no macro calls, so the second scan does
314not change it.  If the actual argument were substituted as given, with
315no prescan, the single remaining scan would find the same macro calls
316and produce the same results.
317
318   You might expect the double scan to change the results when a
319self-referential macro is used in an actual argument of another macro
320(*note Self-Reference::.): the self-referential macro would be expanded
321once in the first scan, and a second time in the second scan.  But this
322is not what happens.  The self-references that do not expand in the
323first scan are marked so that they will not expand in the second scan
324either.
325
326   The prescan is not done when an argument is stringified or
327concatenated.  Thus,
328
329     #define str(s) #s
330     #define foo 4
331     str (foo)
332
333expands to `"foo"'.  Once more, prescan has been prevented from having
334any noticeable effect.
335
336   More precisely, stringification and concatenation use the argument as
337written, in un-prescanned form.  The same actual argument would be used
338in prescanned form if it is substituted elsewhere without
339stringification or concatenation.
340
341     #define str(s) #s lose(s)
342     #define foo 4
343     str (foo)
344
345   expands to `"foo" lose(4)'.
346
347   You might now ask, "Why mention the prescan, if it makes no
348difference?  And why not skip it and make the preprocessor faster?"
349The answer is that the prescan does make a difference in three special
350cases:
351
352   * Nested calls to a macro.
353
354   * Macros that call other macros that stringify or concatenate.
355
356   * Macros whose expansions contain unshielded commas.
357
358   We say that "nested" calls to a macro occur when a macro's actual
359argument contains a call to that very macro.  For example, if `f' is a
360macro that expects one argument, `f (f (1))' is a nested pair of calls
361to `f'.  The desired expansion is made by expanding `f (1)' and
362substituting that into the definition of `f'.  The prescan causes the
363expected result to happen.  Without the prescan, `f (1)' itself would
364be substituted as an actual argument, and the inner use of `f' would
365appear during the main scan as an indirect self-reference and would not
366be expanded.  Here, the prescan cancels an undesirable side effect (in
367the medical, not computational, sense of the term) of the special rule
368for self-referential macros.
369
370   But prescan causes trouble in certain other cases of nested macro
371calls.  Here is an example:
372
373     #define foo  a,b
374     #define bar(x) lose(x)
375     #define lose(x) (1 + (x))
376     
377     bar(foo)
378
379We would like `bar(foo)' to turn into `(1 + (foo))', which would then
380turn into `(1 + (a,b))'.  But instead, `bar(foo)' expands into
381`lose(a,b)', and you get an error because `lose' requires a single
382argument.  In this case, the problem is easily solved by the same
383parentheses that ought to be used to prevent misnesting of arithmetic
384operations:
385
386     #define foo (a,b)
387     #define bar(x) lose((x))
388
389   The problem is more serious when the operands of the macro are not
390expressions; for example, when they are statements.  Then parentheses
391are unacceptable because they would make for invalid C code:
392
393     #define foo { int a, b; ... }
394
395In GNU C you can shield the commas using the `({...})' construct which
396turns a compound statement into an expression:
397
398     #define foo ({ int a, b; ... })
399
400   Or you can rewrite the macro definition to avoid such commas:
401
402     #define foo { int a; int b; ... }
403
404   There is also one case where prescan is useful.  It is possible to
405use prescan to expand an argument and then stringify it--if you use two
406levels of macros.  Let's add a new macro `xstr' to the example shown
407above:
408
409     #define xstr(s) str(s)
410     #define str(s) #s
411     #define foo 4
412     xstr (foo)
413
414   This expands into `"4"', not `"foo"'.  The reason for the difference
415is that the argument of `xstr' is expanded at prescan (because `xstr'
416does not specify stringification or concatenation of the argument).
417The result of prescan then forms the actual argument for `str'.  `str'
418uses its argument without prescan because it performs stringification;
419but it cannot prevent or undo the prescanning already done by `xstr'.
420
421
422File: cpp.info,  Node: Cascaded Macros,  Next: Newlines in Args,  Prev: Argument Prescan,  Up: Macro Pitfalls
423
424Cascaded Use of Macros
425......................
426
427   A "cascade" of macros is when one macro's body contains a reference
428to another macro.  This is very common practice.  For example,
429
430     #define BUFSIZE 1020
431     #define TABLESIZE BUFSIZE
432
433   This is not at all the same as defining `TABLESIZE' to be `1020'.
434The `#define' for `TABLESIZE' uses exactly the body you specify--in
435this case, `BUFSIZE'--and does not check to see whether it too is the
436name of a macro.
437
438   It's only when you *use* `TABLESIZE' that the result of its expansion
439is checked for more macro names.
440
441   This makes a difference if you change the definition of `BUFSIZE' at
442some point in the source file.  `TABLESIZE', defined as shown, will
443always expand using the definition of `BUFSIZE' that is currently in
444effect:
445
446     #define BUFSIZE 1020
447     #define TABLESIZE BUFSIZE
448     #undef BUFSIZE
449     #define BUFSIZE 37
450
451Now `TABLESIZE' expands (in two stages) to `37'.  (The `#undef' is to
452prevent any warning about the nontrivial redefinition of `BUFSIZE'.)
453
454
455File: cpp.info,  Node: Newlines in Args,  Prev: Cascaded Macros,  Up: Macro Pitfalls
456
457Newlines in Macro Arguments
458---------------------------
459
460   Traditional macro processing carries forward all newlines in macro
461arguments into the expansion of the macro.  This means that, if some of
462the arguments are substituted more than once, or not at all, or out of
463order, newlines can be duplicated, lost, or moved around within the
464expansion.  If the expansion consists of multiple statements, then the
465effect is to distort the line numbers of some of these statements.  The
466result can be incorrect line numbers, in error messages or displayed in
467a debugger.
468
469   The GNU C preprocessor operating in ANSI C mode adjusts appropriately
470for multiple use of an argument--the first use expands all the
471newlines, and subsequent uses of the same argument produce no newlines.
472But even in this mode, it can produce incorrect line numbering if
473arguments are used out of order, or not used at all.
474
475   Here is an example illustrating this problem:
476
477     #define ignore_second_arg(a,b,c) a; c
478     
479     ignore_second_arg (foo (),
480                        ignored (),
481                        syntax error);
482
483The syntax error triggered by the tokens `syntax error' results in an
484error message citing line four, even though the statement text comes
485from line five.
486
487
488File: cpp.info,  Node: Conditionals,  Next: Combining Sources,  Prev: Macros,  Up: Top
489
490Conditionals
491============
492
493   In a macro processor, a "conditional" is a directive that allows a
494part of the program to be ignored during compilation, on some
495conditions.  In the C preprocessor, a conditional can test either an
496arithmetic expression or whether a name is defined as a macro.
497
498   A conditional in the C preprocessor resembles in some ways an `if'
499statement in C, but it is important to understand the difference between
500them.  The condition in an `if' statement is tested during the execution
501of your program.  Its purpose is to allow your program to behave
502differently from run to run, depending on the data it is operating on.
503The condition in a preprocessing conditional directive is tested when
504your program is compiled.  Its purpose is to allow different code to be
505included in the program depending on the situation at the time of
506compilation.
507
508* Menu:
509
510* Uses: Conditional Uses.       What conditionals are for.
511* Syntax: Conditional Syntax.   How conditionals are written.
512* Deletion: Deleted Code.       Making code into a comment.
513* Macros: Conditionals-Macros.  Why conditionals are used with macros.
514* Assertions::                  How and why to use assertions.
515* Errors: #error Directive.     Detecting inconsistent compilation parameters.
516
517
518File: cpp.info,  Node: Conditional Uses,  Next: Conditional Syntax,  Up: Conditionals
519
520Why Conditionals are Used
521-------------------------
522
523   Generally there are three kinds of reason to use a conditional.
524
525   * A program may need to use different code depending on the machine
526     or operating system it is to run on.  In some cases the code for
527     one operating system may be erroneous on another operating system;
528     for example, it might refer to library routines that do not exist
529     on the other system.  When this happens, it is not enough to avoid
530     executing the invalid code: merely having it in the program makes
531     it impossible to link the program and run it.  With a
532     preprocessing conditional, the offending code can be effectively
533     excised from the program when it is not valid.
534
535   * You may want to be able to compile the same source file into two
536     different programs.  Sometimes the difference between the programs
537     is that one makes frequent time-consuming consistency checks on its
538     intermediate data, or prints the values of those data for
539     debugging, while the other does not.
540
541   * A conditional whose condition is always false is a good way to
542     exclude code from the program but keep it as a sort of comment for
543     future reference.
544
545   Most simple programs that are intended to run on only one machine
546will not need to use preprocessing conditionals.
547
548
549File: cpp.info,  Node: Conditional Syntax,  Next: Deleted Code,  Prev: Conditional Uses,  Up: Conditionals
550
551Syntax of Conditionals
552----------------------
553
554   A conditional in the C preprocessor begins with a "conditional
555directive": `#if', `#ifdef' or `#ifndef'.  *Note Conditionals-Macros::,
556for information on `#ifdef' and `#ifndef'; only `#if' is explained here.
557
558* Menu:
559
560* If: #if Directive.     Basic conditionals using `#if' and `#endif'.
561* Else: #else Directive. Including some text if the condition fails.
562* Elif: #elif Directive. Testing several alternative possibilities.
563
564
565File: cpp.info,  Node: #if Directive,  Next: #else Directive,  Up: Conditional Syntax
566
567The `#if' Directive
568...................
569
570   The `#if' directive in its simplest form consists of
571
572     #if EXPRESSION
573     CONTROLLED TEXT
574     #endif /* EXPRESSION */
575
576   The comment following the `#endif' is not required, but it is a good
577practice because it helps people match the `#endif' to the
578corresponding `#if'.  Such comments should always be used, except in
579short conditionals that are not nested.  In fact, you can put anything
580at all after the `#endif' and it will be ignored by the GNU C
581preprocessor, but only comments are acceptable in ANSI Standard C.
582
583   EXPRESSION is a C expression of integer type, subject to stringent
584restrictions.  It may contain
585
586   * Integer constants, which are all regarded as `long' or `unsigned
587     long'.
588
589   * Character constants, which are interpreted according to the
590     character set and conventions of the machine and operating system
591     on which the preprocessor is running.  The GNU C preprocessor uses
592     the C data type `char' for these character constants; therefore,
593     whether some character codes are negative is determined by the C
594     compiler used to compile the preprocessor.  If it treats `char' as
595     signed, then character codes large enough to set the sign bit will
596     be considered negative; otherwise, no character code is considered
597     negative.
598
599   * Arithmetic operators for addition, subtraction, multiplication,
600     division, bitwise operations, shifts, comparisons, and logical
601     operations (`&&' and `||').
602
603   * Identifiers that are not macros, which are all treated as zero(!).
604
605   * Macro calls.  All macro calls in the expression are expanded before
606     actual computation of the expression's value begins.
607
608   Note that `sizeof' operators and `enum'-type values are not allowed.
609`enum'-type values, like all other identifiers that are not taken as
610macro calls and expanded, are treated as zero.
611
612   The CONTROLLED TEXT inside of a conditional can include
613preprocessing directives.  Then the directives inside the conditional
614are obeyed only if that branch of the conditional succeeds.  The text
615can also contain other conditional groups.  However, the `#if' and
616`#endif' directives must balance.
617
618
619File: cpp.info,  Node: #else Directive,  Next: #elif Directive,  Prev: #if Directive,  Up: Conditional Syntax
620
621The `#else' Directive
622.....................
623
624   The `#else' directive can be added to a conditional to provide
625alternative text to be used if the condition is false.  This is what it
626looks like:
627
628     #if EXPRESSION
629     TEXT-IF-TRUE
630     #else /* Not EXPRESSION */
631     TEXT-IF-FALSE
632     #endif /* Not EXPRESSION */
633
634   If EXPRESSION is nonzero, and thus the TEXT-IF-TRUE is active, then
635`#else' acts like a failing conditional and the TEXT-IF-FALSE is
636ignored.  Contrariwise, if the `#if' conditional fails, the
637TEXT-IF-FALSE is considered included.
638
639
640File: cpp.info,  Node: #elif Directive,  Prev: #else Directive,  Up: Conditional Syntax
641
642The `#elif' Directive
643.....................
644
645   One common case of nested conditionals is used to check for more
646than two possible alternatives.  For example, you might have
647
648     #if X == 1
649     ...
650     #else /* X != 1 */
651     #if X == 2
652     ...
653     #else /* X != 2 */
654     ...
655     #endif /* X != 2 */
656     #endif /* X != 1 */
657
658   Another conditional directive, `#elif', allows this to be abbreviated
659as follows:
660
661     #if X == 1
662     ...
663     #elif X == 2
664     ...
665     #else /* X != 2 and X != 1*/
666     ...
667     #endif /* X != 2 and X != 1*/
668
669   `#elif' stands for "else if".  Like `#else', it goes in the middle
670of a `#if'-`#endif' pair and subdivides it; it does not require a
671matching `#endif' of its own.  Like `#if', the `#elif' directive
672includes an expression to be tested.
673
674   The text following the `#elif' is processed only if the original
675`#if'-condition failed and the `#elif' condition succeeds.  More than
676one `#elif' can go in the same `#if'-`#endif' group.  Then the text
677after each `#elif' is processed only if the `#elif' condition succeeds
678after the original `#if' and any previous `#elif' directives within it
679have failed.  `#else' is equivalent to `#elif 1', and `#else' is
680allowed after any number of `#elif' directives, but `#elif' may not
681follow `#else'.
682
683
684File: cpp.info,  Node: Deleted Code,  Next: Conditionals-Macros,  Prev: Conditional Syntax,  Up: Conditionals
685
686Keeping Deleted Code for Future Reference
687-----------------------------------------
688
689   If you replace or delete a part of the program but want to keep the
690old code around as a comment for future reference, the easy way to do
691this is to put `#if 0' before it and `#endif' after it.  This is better
692than using comment delimiters `/*' and `*/' since those won't work if
693the code already contains comments (C comments do not nest).
694
695   This works even if the code being turned off contains conditionals,
696but they must be entire conditionals (balanced `#if' and `#endif').
697
698   Conversely, do not use `#if 0' for comments which are not C code.
699Use the comment delimiters `/*' and `*/' instead.  The interior of `#if
7000' must consist of complete tokens; in particular, singlequote
701characters must balance.  But comments often contain unbalanced
702singlequote characters (known in English as apostrophes).  These
703confuse `#if 0'.  They do not confuse `/*'.
704
705
706File: cpp.info,  Node: Conditionals-Macros,  Next: Assertions,  Prev: Deleted Code,  Up: Conditionals
707
708Conditionals and Macros
709-----------------------
710
711   Conditionals are useful in connection with macros or assertions,
712because those are the only ways that an expression's value can vary
713from one compilation to another.  A `#if' directive whose expression
714uses no macros or assertions is equivalent to `#if 1' or `#if 0'; you
715might as well determine which one, by computing the value of the
716expression yourself, and then simplify the program.
717
718   For example, here is a conditional that tests the expression
719`BUFSIZE == 1020', where `BUFSIZE' must be a macro.
720
721     #if BUFSIZE == 1020
722       printf ("Large buffers!\n");
723     #endif /* BUFSIZE is large */
724
725   (Programmers often wish they could test the size of a variable or
726data type in `#if', but this does not work.  The preprocessor does not
727understand `sizeof', or typedef names, or even the type keywords such
728as `int'.)
729
730   The special operator `defined' is used in `#if' expressions to test
731whether a certain name is defined as a macro.  Either `defined NAME' or
732`defined (NAME)' is an expression whose value is 1 if NAME is defined
733as macro at the current point in the program, and 0 otherwise.  For the
734`defined' operator it makes no difference what the definition of the
735macro is; all that matters is whether there is a definition.  Thus, for
736example,
737
738     #if defined (vax) || defined (ns16000)
739
740would succeed if either of the names `vax' and `ns16000' is defined as
741a macro.  You can test the same condition using assertions (*note
742Assertions::.), like this:
743
744     #if #cpu (vax) || #cpu (ns16000)
745
746   If a macro is defined and later undefined with `#undef', subsequent
747use of the `defined' operator returns 0, because the name is no longer
748defined.  If the macro is defined again with another `#define',
749`defined' will recommence returning 1.
750
751   Conditionals that test whether just one name is defined are very
752common, so there are two special short conditional directives for this
753case.
754
755`#ifdef NAME'
756     is equivalent to `#if defined (NAME)'.
757
758`#ifndef NAME'
759     is equivalent to `#if ! defined (NAME)'.
760
761   Macro definitions can vary between compilations for several reasons.
762
763   * Some macros are predefined on each kind of machine.  For example,
764     on a Vax, the name `vax' is a predefined macro.  On other
765     machines, it would not be defined.
766
767   * Many more macros are defined by system header files.  Different
768     systems and machines define different macros, or give them
769     different values.  It is useful to test these macros with
770     conditionals to avoid using a system feature on a machine where it
771     is not implemented.
772
773   * Macros are a common way of allowing users to customize a program
774     for different machines or applications.  For example, the macro
775     `BUFSIZE' might be defined in a configuration file for your
776     program that is included as a header file in each source file.  You
777     would use `BUFSIZE' in a preprocessing conditional in order to
778     generate different code depending on the chosen configuration.
779
780   * Macros can be defined or undefined with `-D' and `-U' command
781     options when you compile the program.  You can arrange to compile
782     the same source file into two different programs by choosing a
783     macro name to specify which program you want, writing conditionals
784     to test whether or how this macro is defined, and then controlling
785     the state of the macro with compiler command options.  *Note
786     Invocation::.
787
788   Assertions are usually predefined, but can be defined with
789preprocessor directives or command-line options.
790
791
792File: cpp.info,  Node: Assertions,  Next: #error Directive,  Prev: Conditionals-Macros,  Up: Conditionals
793
794Assertions
795----------
796
797   "Assertions" are a more systematic alternative to macros in writing
798conditionals to test what sort of computer or system the compiled
799program will run on.  Assertions are usually predefined, but you can
800define them with preprocessing directives or command-line options.
801
802   The macros traditionally used to describe the type of target are not
803classified in any way according to which question they answer; they may
804indicate a hardware architecture, a particular hardware model, an
805operating system, a particular version of an operating system, or
806specific configuration options.  These are jumbled together in a single
807namespace.  In contrast, each assertion consists of a named question and
808an answer.  The question is usually called the "predicate".  An
809assertion looks like this:
810
811     #PREDICATE (ANSWER)
812
813You must use a properly formed identifier for PREDICATE.  The value of
814ANSWER can be any sequence of words; all characters are significant
815except for leading and trailing whitespace, and differences in internal
816whitespace sequences are ignored.  Thus, `x + y' is different from
817`x+y' but equivalent to `x + y'.  `)' is not allowed in an answer.
818
819   Here is a conditional to test whether the answer ANSWER is asserted
820for the predicate PREDICATE:
821
822     #if #PREDICATE (ANSWER)
823
824There may be more than one answer asserted for a given predicate.  If
825you omit the answer, you can test whether *any* answer is asserted for
826PREDICATE:
827
828     #if #PREDICATE
829
830   Most of the time, the assertions you test will be predefined
831assertions.  GNU C provides three predefined predicates: `system',
832`cpu', and `machine'.  `system' is for assertions about the type of
833software, `cpu' describes the type of computer architecture, and
834`machine' gives more information about the computer.  For example, on a
835GNU system, the following assertions would be true:
836
837     #system (gnu)
838     #system (mach)
839     #system (mach 3)
840     #system (mach 3.SUBVERSION)
841     #system (hurd)
842     #system (hurd VERSION)
843
844and perhaps others.  The alternatives with more or less version
845information let you ask more or less detailed questions about the type
846of system software.
847
848   On a Unix system, you would find `#system (unix)' and perhaps one of:
849`#system (aix)', `#system (bsd)', `#system (hpux)', `#system (lynx)',
850`#system (mach)', `#system (posix)', `#system (svr3)', `#system
851(svr4)', or `#system (xpg4)' with possible version numbers following.
852
853   Other values for `system' are `#system (mvs)' and `#system (vms)'.
854
855   *Portability note:* Many Unix C compilers provide only one answer
856for the `system' assertion: `#system (unix)', if they support
857assertions at all.  This is less than useful.
858
859   An assertion with a multi-word answer is completely different from
860several assertions with individual single-word answers.  For example,
861the presence of `system (mach 3.0)' does not mean that `system (3.0)'
862is true.  It also does not directly imply `system (mach)', but in GNU
863C, that last will normally be asserted as well.
864
865   The current list of possible assertion values for `cpu' is: `#cpu
866(a29k)', `#cpu (alpha)', `#cpu (arm)', `#cpu (clipper)', `#cpu
867(convex)', `#cpu (elxsi)', `#cpu (tron)', `#cpu (h8300)', `#cpu
868(i370)', `#cpu (i386)', `#cpu (i860)', `#cpu (i960)', `#cpu (m68k)',
869`#cpu (m88k)', `#cpu (mips)', `#cpu (ns32k)', `#cpu (hppa)', `#cpu
870(pyr)', `#cpu (ibm032)', `#cpu (rs6000)', `#cpu (sh)', `#cpu (sparc)',
871`#cpu (spur)', `#cpu (tahoe)', `#cpu (vax)', `#cpu (we32000)'.
872
873   You can create assertions within a C program using `#assert', like
874this:
875
876     #assert PREDICATE (ANSWER)
877
878(Note the absence of a `#' before PREDICATE.)
879
880   Each time you do this, you assert a new true answer for PREDICATE.
881Asserting one answer does not invalidate previously asserted answers;
882they all remain true.  The only way to remove an assertion is with
883`#unassert'.  `#unassert' has the same syntax as `#assert'.  You can
884also remove all assertions about PREDICATE like this:
885
886     #unassert PREDICATE
887
888   You can also add or cancel assertions using command options when you
889run `gcc' or `cpp'.  *Note Invocation::.
890
891
892File: cpp.info,  Node: #error Directive,  Prev: Assertions,  Up: Conditionals
893
894The `#error' and `#warning' Directives
895--------------------------------------
896
897   The directive `#error' causes the preprocessor to report a fatal
898error.  The rest of the line that follows `#error' is used as the error
899message.  The line must consist of complete tokens.
900
901   You would use `#error' inside of a conditional that detects a
902combination of parameters which you know the program does not properly
903support.  For example, if you know that the program will not run
904properly on a Vax, you might write
905
906     #ifdef __vax__
907     #error "Won't work on Vaxen.  See comments at get_last_object."
908     #endif
909
910*Note Nonstandard Predefined::, for why this works.
911
912   If you have several configuration parameters that must be set up by
913the installation in a consistent way, you can use conditionals to detect
914an inconsistency and report it with `#error'.  For example,
915
916     #if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \
917         || HASH_TABLE_SIZE % 5 == 0
918     #error HASH_TABLE_SIZE should not be divisible by a small prime
919     #endif
920
921   The directive `#warning' is like the directive `#error', but causes
922the preprocessor to issue a warning and continue preprocessing.  The
923rest of the line that follows `#warning' is used as the warning message.
924
925   You might use `#warning' in obsolete header files, with a message
926directing the user to the header file which should be used instead.
927
928
929File: cpp.info,  Node: Combining Sources,  Next: Other Directives,  Prev: Conditionals,  Up: Top
930
931Combining Source Files
932======================
933
934   One of the jobs of the C preprocessor is to inform the C compiler of
935where each line of C code came from: which source file and which line
936number.
937
938   C code can come from multiple source files if you use `#include';
939both `#include' and the use of conditionals and macros can cause the
940line number of a line in the preprocessor output to be different from
941the line's number in the original source file.  You will appreciate the
942value of making both the C compiler (in error messages) and symbolic
943debuggers such as GDB use the line numbers in your source file.
944
945   The C preprocessor builds on this feature by offering a directive by
946which you can control the feature explicitly.  This is useful when a
947file for input to the C preprocessor is the output from another program
948such as the `bison' parser generator, which operates on another file
949that is the true source file.  Parts of the output from `bison' are
950generated from scratch, other parts come from a standard parser file.
951The rest are copied nearly verbatim from the source file, but their
952line numbers in the `bison' output are not the same as their original
953line numbers.  Naturally you would like compiler error messages and
954symbolic debuggers to know the original source file and line number of
955each line in the `bison' input.
956
957   `bison' arranges this by writing `#line' directives into the output
958file.  `#line' is a directive that specifies the original line number
959and source file name for subsequent input in the current preprocessor
960input file.  `#line' has three variants:
961
962`#line LINENUM'
963     Here LINENUM is a decimal integer constant.  This specifies that
964     the line number of the following line of input, in its original
965     source file, was LINENUM.
966
967`#line LINENUM FILENAME'
968     Here LINENUM is a decimal integer constant and FILENAME is a
969     string constant.  This specifies that the following line of input
970     came originally from source file FILENAME and its line number there
971     was LINENUM.  Keep in mind that FILENAME is not just a file name;
972     it is surrounded by doublequote characters so that it looks like a
973     string constant.
974
975`#line ANYTHING ELSE'
976     ANYTHING ELSE is checked for macro calls, which are expanded.  The
977     result should be a decimal integer constant followed optionally by
978     a string constant, as described above.
979
980   `#line' directives alter the results of the `__FILE__' and
981`__LINE__' predefined macros from that point on.  *Note Standard
982Predefined::.
983
984   The output of the preprocessor (which is the input for the rest of
985the compiler) contains directives that look much like `#line'
986directives.  They start with just `#' instead of `#line', but this is
987followed by a line number and file name as in `#line'.  *Note Output::.
988
989
990File: cpp.info,  Node: Other Directives,  Next: Output,  Prev: Combining Sources,  Up: Top
991
992Miscellaneous Preprocessing Directives
993======================================
994
995   This section describes three additional preprocessing directives.
996They are not very useful, but are mentioned for completeness.
997
998   The "null directive" consists of a `#' followed by a Newline, with
999only whitespace (including comments) in between.  A null directive is
1000understood as a preprocessing directive but has no effect on the
1001preprocessor output.  The primary significance of the existence of the
1002null directive is that an input line consisting of just a `#' will
1003produce no output, rather than a line of output containing just a `#'.
1004Supposedly some old C programs contain such lines.
1005
1006   The ANSI standard specifies that the effect of the `#pragma'
1007directive is implementation-defined.  In the GNU C preprocessor,
1008`#pragma' directives are not used, except for `#pragma once' (*note
1009Once-Only::.).  However, they are left in the preprocessor output, so
1010they are available to the compilation pass.
1011
1012   The `#ident' directive is supported for compatibility with certain
1013other systems.  It is followed by a line of text.  On some systems, the
1014text is copied into a special place in the object file; on most systems,
1015the text is ignored and this directive has no effect.  Typically
1016`#ident' is only used in header files supplied with those systems where
1017it is meaningful.
1018
1019
1020File: cpp.info,  Node: Output,  Next: Invocation,  Prev: Other Directives,  Up: Top
1021
1022C Preprocessor Output
1023=====================
1024
1025   The output from the C preprocessor looks much like the input, except
1026that all preprocessing directive lines have been replaced with blank
1027lines and all comments with spaces.  Whitespace within a line is not
1028altered; however, unless `-traditional' is used, spaces may be inserted
1029into the expansions of macro calls to prevent tokens from being
1030concatenated.
1031
1032   Source file name and line number information is conveyed by lines of
1033the form
1034
1035     # LINENUM FILENAME FLAGS
1036
1037which are inserted as needed into the middle of the input (but never
1038within a string or character constant).  Such a line means that the
1039following line originated in file FILENAME at line LINENUM.
1040
1041   After the file name comes zero or more flags, which are `1', `2',
1042`3', or `4'.  If there are multiple flags, spaces separate them.  Here
1043is what the flags mean:
1044
1045`1'
1046     This indicates the start of a new file.
1047
1048`2'
1049     This indicates returning to a file (after having included another
1050     file).
1051
1052`3'
1053     This indicates that the following text comes from a system header
1054     file, so certain warnings should be suppressed.
1055
1056`4'
1057     This indicates that the following text should be treated as C.
1058
Note: See TracBrowser for help on using the repository browser.