Initial import from FreeBSD RELENG_4:
[games.git] / contrib / gcc / extend.texi
1 @c Copyright (C) 1988,89,92,93,94,96,99 Free Software Foundation, Inc.
2 @c This is part of the GCC manual.
3 @c For copying conditions, see the file gcc.texi.
4
5 @c $FreeBSD: src/contrib/gcc/extend.texi,v 1.4 1999/10/27 09:41:10 obrien Exp $
6
7 @node C Extensions
8 @chapter Extensions to the C Language Family
9 @cindex extensions, C language
10 @cindex C language extensions
11
12 GNU C provides several language features not found in ANSI standard C.
13 (The @samp{-pedantic} option directs GNU CC to print a warning message if
14 any of these features is used.)  To test for the availability of these
15 features in conditional compilation, check for a predefined macro
16 @code{__GNUC__}, which is always defined under GNU CC.
17
18 These extensions are available in C and Objective C.  Most of them are
19 also available in C++.  @xref{C++ Extensions,,Extensions to the
20 C++ Language}, for extensions that apply @emph{only} to C++.
21
22 @c The only difference between the two versions of this menu is that the
23 @c version for clear INTERNALS has an extra node, "Constraints" (which
24 @c appears in a separate chapter in the other version of the manual).
25 @ifset INTERNALS
26 @menu
27 * Statement Exprs::     Putting statements and declarations inside expressions.
28 * Local Labels::        Labels local to a statement-expression.
29 * Labels as Values::    Getting pointers to labels, and computed gotos.
30 * Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
31 * Constructing Calls::  Dispatching a call to another function.
32 * Naming Types::        Giving a name to the type of some expression.
33 * Typeof::              @code{typeof}: referring to the type of an expression.
34 * Lvalues::             Using @samp{?:}, @samp{,} and casts in lvalues.
35 * Conditionals::        Omitting the middle operand of a @samp{?:} expression.
36 * Long Long::           Double-word integers---@code{long long int}.
37 * Complex::             Data types for complex numbers.
38 * Hex Floats::          Hexadecimal floating-point constants.
39 * Zero Length::         Zero-length arrays.
40 * Variable Length::     Arrays whose length is computed at run time.
41 * Macro Varargs::       Macros with variable number of arguments.
42 * Subscripting::        Any array can be subscripted, even if not an lvalue.
43 * Pointer Arith::       Arithmetic on @code{void}-pointers and function pointers.
44 * Initializers::        Non-constant initializers.
45 * Constructors::        Constructor expressions give structures, unions
46                          or arrays as values.
47 * Labeled Elements::    Labeling elements of initializers.
48 * Cast to Union::       Casting to union type from any member of the union.
49 * Case Ranges::         `case 1 ... 9' and such.
50 * Function Attributes:: Declaring that functions have no side effects,
51                          or that they can never return.
52 * Function Prototypes:: Prototype declarations and old-style definitions.
53 * C++ Comments::        C++ comments are recognized.
54 * Dollar Signs::        Dollar sign is allowed in identifiers.
55 * Character Escapes::   @samp{\e} stands for the character @key{ESC}.
56 * Variable Attributes:: Specifying attributes of variables.
57 * Type Attributes::     Specifying attributes of types.
58 * Alignment::           Inquiring about the alignment of a type or variable.
59 * Inline::              Defining inline functions (as fast as macros).
60 * Extended Asm::        Assembler instructions with C expressions as operands.
61                          (With them you can define ``built-in'' functions.)
62 * Asm Labels::          Specifying the assembler name to use for a C symbol.
63 * Explicit Reg Vars::   Defining variables residing in specified registers.
64 * Alternate Keywords::  @code{__const__}, @code{__asm__}, etc., for header files.
65 * Incomplete Enums::    @code{enum foo;}, with details to follow.
66 * Function Names::      Printable strings which are the name of the current
67                          function.
68 * Return Address::      Getting the return or frame address of a function.
69 * Other Builtins::      Other built-in functions.
70 * Deprecated Features:: Things might disappear from g++.
71 @end menu
72 @end ifset
73 @ifclear INTERNALS
74 @menu
75 * Statement Exprs::     Putting statements and declarations inside expressions.
76 * Local Labels::        Labels local to a statement-expression.
77 * Labels as Values::    Getting pointers to labels, and computed gotos.
78 * Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
79 * Constructing Calls::  Dispatching a call to another function.
80 * Naming Types::        Giving a name to the type of some expression.
81 * Typeof::              @code{typeof}: referring to the type of an expression.
82 * Lvalues::             Using @samp{?:}, @samp{,} and casts in lvalues.
83 * Conditionals::        Omitting the middle operand of a @samp{?:} expression.
84 * Long Long::           Double-word integers---@code{long long int}.
85 * Complex::             Data types for complex numbers.
86 * Hex Floats::          Hexadecimal floating-point constants.
87 * Zero Length::         Zero-length arrays.
88 * Variable Length::     Arrays whose length is computed at run time.
89 * Macro Varargs::       Macros with variable number of arguments.
90 * Subscripting::        Any array can be subscripted, even if not an lvalue.
91 * Pointer Arith::       Arithmetic on @code{void}-pointers and function pointers.
92 * Initializers::        Non-constant initializers.
93 * Constructors::        Constructor expressions give structures, unions
94                          or arrays as values.
95 * Labeled Elements::    Labeling elements of initializers.
96 * Cast to Union::       Casting to union type from any member of the union.
97 * Case Ranges::         `case 1 ... 9' and such.
98 * Function Attributes:: Declaring that functions have no side effects,
99                          or that they can never return.
100 * Function Prototypes:: Prototype declarations and old-style definitions.
101 * C++ Comments::        C++ comments are recognized.
102 * Dollar Signs::        Dollar sign is allowed in identifiers.
103 * Character Escapes::   @samp{\e} stands for the character @key{ESC}.
104 * Variable Attributes:: Specifying attributes of variables.
105 * Type Attributes::     Specifying attributes of types.
106 * Alignment::           Inquiring about the alignment of a type or variable.
107 * Inline::              Defining inline functions (as fast as macros).
108 * Extended Asm::        Assembler instructions with C expressions as operands.
109                          (With them you can define ``built-in'' functions.)
110 * Constraints::         Constraints for asm operands
111 * Asm Labels::          Specifying the assembler name to use for a C symbol.
112 * Explicit Reg Vars::   Defining variables residing in specified registers.
113 * Alternate Keywords::  @code{__const__}, @code{__asm__}, etc., for header files.
114 * Incomplete Enums::    @code{enum foo;}, with details to follow.
115 * Function Names::      Printable strings which are the name of the current
116                          function.
117 * Return Address::      Getting the return or frame address of a function.
118 * Deprecated Features:: Things might disappear from g++.
119 @end menu
120 @end ifclear
121
122 @node Statement Exprs
123 @section Statements and Declarations in Expressions
124 @cindex statements inside expressions
125 @cindex declarations inside expressions
126 @cindex expressions containing statements
127 @cindex macros, statements in expressions
128
129 @c the above section title wrapped and causes an underfull hbox.. i
130 @c changed it from "within" to "in". --mew 4feb93
131
132 A compound statement enclosed in parentheses may appear as an expression
133 in GNU C.  This allows you to use loops, switches, and local variables
134 within an expression.
135
136 Recall that a compound statement is a sequence of statements surrounded
137 by braces; in this construct, parentheses go around the braces.  For
138 example:
139
140 @example
141 (@{ int y = foo (); int z;
142    if (y > 0) z = y;
143    else z = - y;
144    z; @})
145 @end example
146
147 @noindent
148 is a valid (though slightly more complex than necessary) expression
149 for the absolute value of @code{foo ()}.
150
151 The last thing in the compound statement should be an expression
152 followed by a semicolon; the value of this subexpression serves as the
153 value of the entire construct.  (If you use some other kind of statement
154 last within the braces, the construct has type @code{void}, and thus
155 effectively no value.)
156
157 This feature is especially useful in making macro definitions ``safe'' (so
158 that they evaluate each operand exactly once).  For example, the
159 ``maximum'' function is commonly defined as a macro in standard C as
160 follows:
161
162 @example
163 #define max(a,b) ((a) > (b) ? (a) : (b))
164 @end example
165
166 @noindent
167 @cindex side effects, macro argument
168 But this definition computes either @var{a} or @var{b} twice, with bad
169 results if the operand has side effects.  In GNU C, if you know the
170 type of the operands (here let's assume @code{int}), you can define
171 the macro safely as follows:
172
173 @example
174 #define maxint(a,b) \
175   (@{int _a = (a), _b = (b); _a > _b ? _a : _b; @})
176 @end example
177
178 Embedded statements are not allowed in constant expressions, such as
179 the value of an enumeration constant, the width of a bit field, or
180 the initial value of a static variable.
181
182 If you don't know the type of the operand, you can still do this, but you
183 must use @code{typeof} (@pxref{Typeof}) or type naming (@pxref{Naming
184 Types}).
185
186 @node Local Labels
187 @section Locally Declared Labels
188 @cindex local labels
189 @cindex macros, local labels
190
191 Each statement expression is a scope in which @dfn{local labels} can be
192 declared.  A local label is simply an identifier; you can jump to it
193 with an ordinary @code{goto} statement, but only from within the
194 statement expression it belongs to.
195
196 A local label declaration looks like this:
197
198 @example
199 __label__ @var{label};
200 @end example
201
202 @noindent
203 or
204
205 @example
206 __label__ @var{label1}, @var{label2}, @dots{};
207 @end example
208
209 Local label declarations must come at the beginning of the statement
210 expression, right after the @samp{(@{}, before any ordinary
211 declarations.
212
213 The label declaration defines the label @emph{name}, but does not define
214 the label itself.  You must do this in the usual way, with
215 @code{@var{label}:}, within the statements of the statement expression.
216
217 The local label feature is useful because statement expressions are
218 often used in macros.  If the macro contains nested loops, a @code{goto}
219 can be useful for breaking out of them.  However, an ordinary label
220 whose scope is the whole function cannot be used: if the macro can be
221 expanded several times in one function, the label will be multiply
222 defined in that function.  A local label avoids this problem.  For
223 example:
224
225 @example
226 #define SEARCH(array, target)                     \
227 (@{                                               \
228   __label__ found;                                \
229   typeof (target) _SEARCH_target = (target);      \
230   typeof (*(array)) *_SEARCH_array = (array);     \
231   int i, j;                                       \
232   int value;                                      \
233   for (i = 0; i < max; i++)                       \
234     for (j = 0; j < max; j++)                     \
235       if (_SEARCH_array[i][j] == _SEARCH_target)  \
236         @{ value = i; goto found; @}              \
237   value = -1;                                     \
238  found:                                           \
239   value;                                          \
240 @})
241 @end example
242
243 @node Labels as Values
244 @section Labels as Values
245 @cindex labels as values
246 @cindex computed gotos
247 @cindex goto with computed label
248 @cindex address of a label
249
250 You can get the address of a label defined in the current function
251 (or a containing function) with the unary operator @samp{&&}.  The
252 value has type @code{void *}.  This value is a constant and can be used
253 wherever a constant of that type is valid.  For example:
254
255 @example
256 void *ptr;
257 @dots{}
258 ptr = &&foo;
259 @end example
260
261 To use these values, you need to be able to jump to one.  This is done
262 with the computed goto statement@footnote{The analogous feature in
263 Fortran is called an assigned goto, but that name seems inappropriate in
264 C, where one can do more than simply store label addresses in label
265 variables.}, @code{goto *@var{exp};}.  For example,
266
267 @example
268 goto *ptr;
269 @end example
270
271 @noindent
272 Any expression of type @code{void *} is allowed.
273
274 One way of using these constants is in initializing a static array that
275 will serve as a jump table:
276
277 @example
278 static void *array[] = @{ &&foo, &&bar, &&hack @};
279 @end example
280
281 Then you can select a label with indexing, like this:
282
283 @example
284 goto *array[i];
285 @end example
286
287 @noindent
288 Note that this does not check whether the subscript is in bounds---array
289 indexing in C never does that.
290
291 Such an array of label values serves a purpose much like that of the
292 @code{switch} statement.  The @code{switch} statement is cleaner, so
293 use that rather than an array unless the problem does not fit a
294 @code{switch} statement very well.
295
296 Another use of label values is in an interpreter for threaded code.
297 The labels within the interpreter function can be stored in the
298 threaded code for super-fast dispatching.
299
300 You can use this mechanism to jump to code in a different function.  If
301 you do that, totally unpredictable things will happen.  The best way to
302 avoid this is to store the label address only in automatic variables and
303 never pass it as an argument.
304
305 @node Nested Functions
306 @section Nested Functions
307 @cindex nested functions
308 @cindex downward funargs
309 @cindex thunks
310
311 A @dfn{nested function} is a function defined inside another function.
312 (Nested functions are not supported for GNU C++.)  The nested function's
313 name is local to the block where it is defined.  For example, here we
314 define a nested function named @code{square}, and call it twice:
315
316 @example
317 @group
318 foo (double a, double b)
319 @{
320   double square (double z) @{ return z * z; @}
321
322   return square (a) + square (b);
323 @}
324 @end group
325 @end example
326
327 The nested function can access all the variables of the containing
328 function that are visible at the point of its definition.  This is
329 called @dfn{lexical scoping}.  For example, here we show a nested
330 function which uses an inherited variable named @code{offset}:
331
332 @example
333 bar (int *array, int offset, int size)
334 @{
335   int access (int *array, int index)
336     @{ return array[index + offset]; @}
337   int i;
338   @dots{}
339   for (i = 0; i < size; i++)
340     @dots{} access (array, i) @dots{}
341 @}
342 @end example
343
344 Nested function definitions are permitted within functions in the places
345 where variable definitions are allowed; that is, in any block, before
346 the first statement in the block.
347
348 It is possible to call the nested function from outside the scope of its
349 name by storing its address or passing the address to another function:
350
351 @example
352 hack (int *array, int size)
353 @{
354   void store (int index, int value)
355     @{ array[index] = value; @}
356
357   intermediate (store, size);
358 @}
359 @end example
360
361 Here, the function @code{intermediate} receives the address of
362 @code{store} as an argument.  If @code{intermediate} calls @code{store},
363 the arguments given to @code{store} are used to store into @code{array}.
364 But this technique works only so long as the containing function
365 (@code{hack}, in this example) does not exit.
366
367 If you try to call the nested function through its address after the
368 containing function has exited, all hell will break loose.  If you try
369 to call it after a containing scope level has exited, and if it refers
370 to some of the variables that are no longer in scope, you may be lucky,
371 but it's not wise to take the risk.  If, however, the nested function
372 does not refer to anything that has gone out of scope, you should be
373 safe.
374
375 GNU CC implements taking the address of a nested function using a
376 technique called @dfn{trampolines}.   A paper describing them is
377 available as @samp{http://master.debian.org/~karlheg/Usenix88-lexic.pdf}.
378
379 A nested function can jump to a label inherited from a containing
380 function, provided the label was explicitly declared in the containing
381 function (@pxref{Local Labels}).  Such a jump returns instantly to the
382 containing function, exiting the nested function which did the
383 @code{goto} and any intermediate functions as well.  Here is an example:
384
385 @example
386 @group
387 bar (int *array, int offset, int size)
388 @{
389   __label__ failure;
390   int access (int *array, int index)
391     @{
392       if (index > size)
393         goto failure;
394       return array[index + offset];
395     @}
396   int i;
397   @dots{}
398   for (i = 0; i < size; i++)
399     @dots{} access (array, i) @dots{}
400   @dots{}
401   return 0;
402
403  /* @r{Control comes here from @code{access}
404     if it detects an error.}  */
405  failure:
406   return -1;
407 @}
408 @end group
409 @end example
410
411 A nested function always has internal linkage.  Declaring one with
412 @code{extern} is erroneous.  If you need to declare the nested function
413 before its definition, use @code{auto} (which is otherwise meaningless
414 for function declarations).
415
416 @example
417 bar (int *array, int offset, int size)
418 @{
419   __label__ failure;
420   auto int access (int *, int);
421   @dots{}
422   int access (int *array, int index)
423     @{
424       if (index > size)
425         goto failure;
426       return array[index + offset];
427     @}
428   @dots{}
429 @}
430 @end example
431
432 @node Constructing Calls
433 @section Constructing Function Calls
434 @cindex constructing calls
435 @cindex forwarding calls
436
437 Using the built-in functions described below, you can record
438 the arguments a function received, and call another function
439 with the same arguments, without knowing the number or types
440 of the arguments.
441
442 You can also record the return value of that function call,
443 and later return that value, without knowing what data type
444 the function tried to return (as long as your caller expects
445 that data type).
446
447 @table @code
448 @findex __builtin_apply_args
449 @item __builtin_apply_args ()
450 This built-in function returns a pointer of type @code{void *} to data
451 describing how to perform a call with the same arguments as were passed
452 to the current function.
453
454 The function saves the arg pointer register, structure value address,
455 and all registers that might be used to pass arguments to a function
456 into a block of memory allocated on the stack.  Then it returns the
457 address of that block.
458
459 @findex __builtin_apply
460 @item __builtin_apply (@var{function}, @var{arguments}, @var{size})
461 This built-in function invokes @var{function} (type @code{void (*)()})
462 with a copy of the parameters described by @var{arguments} (type
463 @code{void *}) and @var{size} (type @code{int}).
464
465 The value of @var{arguments} should be the value returned by
466 @code{__builtin_apply_args}.  The argument @var{size} specifies the size
467 of the stack argument data, in bytes.
468
469 This function returns a pointer of type @code{void *} to data describing
470 how to return whatever value was returned by @var{function}.  The data
471 is saved in a block of memory allocated on the stack.
472
473 It is not always simple to compute the proper value for @var{size}.  The
474 value is used by @code{__builtin_apply} to compute the amount of data
475 that should be pushed on the stack and copied from the incoming argument
476 area.
477
478 @findex __builtin_return
479 @item __builtin_return (@var{result})
480 This built-in function returns the value described by @var{result} from
481 the containing function.  You should specify, for @var{result}, a value
482 returned by @code{__builtin_apply}.
483 @end table
484
485 @node Naming Types
486 @section Naming an Expression's Type
487 @cindex naming types
488
489 You can give a name to the type of an expression using a @code{typedef}
490 declaration with an initializer.  Here is how to define @var{name} as a
491 type name for the type of @var{exp}:
492
493 @example
494 typedef @var{name} = @var{exp};
495 @end example
496
497 This is useful in conjunction with the statements-within-expressions
498 feature.  Here is how the two together can be used to define a safe
499 ``maximum'' macro that operates on any arithmetic type:
500
501 @example
502 #define max(a,b) \
503   (@{typedef _ta = (a), _tb = (b);  \
504     _ta _a = (a); _tb _b = (b);     \
505     _a > _b ? _a : _b; @})
506 @end example
507
508 @cindex underscores in variables in macros
509 @cindex @samp{_} in variables in macros
510 @cindex local variables in macros
511 @cindex variables, local, in macros
512 @cindex macros, local variables in
513
514 The reason for using names that start with underscores for the local
515 variables is to avoid conflicts with variable names that occur within the
516 expressions that are substituted for @code{a} and @code{b}.  Eventually we
517 hope to design a new form of declaration syntax that allows you to declare
518 variables whose scopes start only after their initializers; this will be a
519 more reliable way to prevent such conflicts.
520
521 @node Typeof
522 @section Referring to a Type with @code{typeof}
523 @findex typeof
524 @findex sizeof
525 @cindex macros, types of arguments
526
527 Another way to refer to the type of an expression is with @code{typeof}.
528 The syntax of using of this keyword looks like @code{sizeof}, but the
529 construct acts semantically like a type name defined with @code{typedef}.
530
531 There are two ways of writing the argument to @code{typeof}: with an
532 expression or with a type.  Here is an example with an expression:
533
534 @example
535 typeof (x[0](1))
536 @end example
537
538 @noindent
539 This assumes that @code{x} is an array of functions; the type described
540 is that of the values of the functions.
541
542 Here is an example with a typename as the argument:
543
544 @example
545 typeof (int *)
546 @end example
547
548 @noindent
549 Here the type described is that of pointers to @code{int}.
550
551 If you are writing a header file that must work when included in ANSI C
552 programs, write @code{__typeof__} instead of @code{typeof}.
553 @xref{Alternate Keywords}.
554
555 A @code{typeof}-construct can be used anywhere a typedef name could be
556 used.  For example, you can use it in a declaration, in a cast, or inside
557 of @code{sizeof} or @code{typeof}.
558
559 @itemize @bullet
560 @item
561 This declares @code{y} with the type of what @code{x} points to.
562
563 @example
564 typeof (*x) y;
565 @end example
566
567 @item
568 This declares @code{y} as an array of such values.
569
570 @example
571 typeof (*x) y[4];
572 @end example
573
574 @item
575 This declares @code{y} as an array of pointers to characters:
576
577 @example
578 typeof (typeof (char *)[4]) y;
579 @end example
580
581 @noindent
582 It is equivalent to the following traditional C declaration:
583
584 @example
585 char *y[4];
586 @end example
587
588 To see the meaning of the declaration using @code{typeof}, and why it
589 might be a useful way to write, let's rewrite it with these macros:
590
591 @example
592 #define pointer(T)  typeof(T *)
593 #define array(T, N) typeof(T [N])
594 @end example
595
596 @noindent
597 Now the declaration can be rewritten this way:
598
599 @example
600 array (pointer (char), 4) y;
601 @end example
602
603 @noindent
604 Thus, @code{array (pointer (char), 4)} is the type of arrays of 4
605 pointers to @code{char}.
606 @end itemize
607
608 @node Lvalues
609 @section Generalized Lvalues
610 @cindex compound expressions as lvalues
611 @cindex expressions, compound, as lvalues
612 @cindex conditional expressions as lvalues
613 @cindex expressions, conditional, as lvalues
614 @cindex casts as lvalues
615 @cindex generalized lvalues
616 @cindex lvalues, generalized
617 @cindex extensions, @code{?:}
618 @cindex @code{?:} extensions
619 Compound expressions, conditional expressions and casts are allowed as
620 lvalues provided their operands are lvalues.  This means that you can take
621 their addresses or store values into them.
622
623 Standard C++ allows compound expressions and conditional expressions as
624 lvalues, and permits casts to reference type, so use of this extension
625 is deprecated for C++ code.
626
627 For example, a compound expression can be assigned, provided the last
628 expression in the sequence is an lvalue.  These two expressions are
629 equivalent:
630
631 @example
632 (a, b) += 5
633 a, (b += 5)
634 @end example
635
636 Similarly, the address of the compound expression can be taken.  These two
637 expressions are equivalent:
638
639 @example
640 &(a, b)
641 a, &b
642 @end example
643
644 A conditional expression is a valid lvalue if its type is not void and the
645 true and false branches are both valid lvalues.  For example, these two
646 expressions are equivalent:
647
648 @example
649 (a ? b : c) = 5
650 (a ? b = 5 : (c = 5))
651 @end example
652
653 A cast is a valid lvalue if its operand is an lvalue.  A simple
654 assignment whose left-hand side is a cast works by converting the
655 right-hand side first to the specified type, then to the type of the
656 inner left-hand side expression.  After this is stored, the value is
657 converted back to the specified type to become the value of the
658 assignment.  Thus, if @code{a} has type @code{char *}, the following two
659 expressions are equivalent:
660
661 @example
662 (int)a = 5
663 (int)(a = (char *)(int)5)
664 @end example
665
666 An assignment-with-arithmetic operation such as @samp{+=} applied to a cast
667 performs the arithmetic using the type resulting from the cast, and then
668 continues as in the previous case.  Therefore, these two expressions are
669 equivalent:
670
671 @example
672 (int)a += 5
673 (int)(a = (char *)(int) ((int)a + 5))
674 @end example
675
676 You cannot take the address of an lvalue cast, because the use of its
677 address would not work out coherently.  Suppose that @code{&(int)f} were
678 permitted, where @code{f} has type @code{float}.  Then the following
679 statement would try to store an integer bit-pattern where a floating
680 point number belongs:
681
682 @example
683 *&(int)f = 1;
684 @end example
685
686 This is quite different from what @code{(int)f = 1} would do---that
687 would convert 1 to floating point and store it.  Rather than cause this
688 inconsistency, we think it is better to prohibit use of @samp{&} on a cast.
689
690 If you really do want an @code{int *} pointer with the address of
691 @code{f}, you can simply write @code{(int *)&f}.
692
693 @node Conditionals
694 @section Conditionals with Omitted Operands
695 @cindex conditional expressions, extensions
696 @cindex omitted middle-operands
697 @cindex middle-operands, omitted
698 @cindex extensions, @code{?:}
699 @cindex @code{?:} extensions
700
701 The middle operand in a conditional expression may be omitted.  Then
702 if the first operand is nonzero, its value is the value of the conditional
703 expression.
704
705 Therefore, the expression
706
707 @example
708 x ? : y
709 @end example
710
711 @noindent
712 has the value of @code{x} if that is nonzero; otherwise, the value of
713 @code{y}.
714
715 This example is perfectly equivalent to
716
717 @example
718 x ? x : y
719 @end example
720
721 @cindex side effect in ?:
722 @cindex ?: side effect
723 @noindent
724 In this simple case, the ability to omit the middle operand is not
725 especially useful.  When it becomes useful is when the first operand does,
726 or may (if it is a macro argument), contain a side effect.  Then repeating
727 the operand in the middle would perform the side effect twice.  Omitting
728 the middle operand uses the value already computed without the undesirable
729 effects of recomputing it.
730
731 @node Long Long
732 @section Double-Word Integers
733 @cindex @code{long long} data types
734 @cindex double-word arithmetic
735 @cindex multiprecision arithmetic
736
737 GNU C supports data types for integers that are twice as long as
738 @code{int}.  Simply write @code{long long int} for a signed integer, or
739 @code{unsigned long long int} for an unsigned integer.  To make an
740 integer constant of type @code{long long int}, add the suffix @code{LL}
741 to the integer.  To make an integer constant of type @code{unsigned long
742 long int}, add the suffix @code{ULL} to the integer.
743
744 You can use these types in arithmetic like any other integer types.
745 Addition, subtraction, and bitwise boolean operations on these types
746 are open-coded on all types of machines.  Multiplication is open-coded
747 if the machine supports fullword-to-doubleword a widening multiply
748 instruction.  Division and shifts are open-coded only on machines that
749 provide special support.  The operations that are not open-coded use
750 special library routines that come with GNU CC.
751
752 There may be pitfalls when you use @code{long long} types for function
753 arguments, unless you declare function prototypes.  If a function
754 expects type @code{int} for its argument, and you pass a value of type
755 @code{long long int}, confusion will result because the caller and the
756 subroutine will disagree about the number of bytes for the argument.
757 Likewise, if the function expects @code{long long int} and you pass
758 @code{int}.  The best way to avoid such problems is to use prototypes.
759
760 @node Complex
761 @section Complex Numbers
762 @cindex complex numbers
763
764 GNU C supports complex data types.  You can declare both complex integer
765 types and complex floating types, using the keyword @code{__complex__}.
766
767 For example, @samp{__complex__ double x;} declares @code{x} as a
768 variable whose real part and imaginary part are both of type
769 @code{double}.  @samp{__complex__ short int y;} declares @code{y} to
770 have real and imaginary parts of type @code{short int}; this is not
771 likely to be useful, but it shows that the set of complex types is
772 complete.
773
774 To write a constant with a complex data type, use the suffix @samp{i} or
775 @samp{j} (either one; they are equivalent).  For example, @code{2.5fi}
776 has type @code{__complex__ float} and @code{3i} has type
777 @code{__complex__ int}.  Such a constant always has a pure imaginary
778 value, but you can form any complex value you like by adding one to a
779 real constant.
780
781 To extract the real part of a complex-valued expression @var{exp}, write
782 @code{__real__ @var{exp}}.  Likewise, use @code{__imag__} to
783 extract the imaginary part.
784
785 The operator @samp{~} performs complex conjugation when used on a value
786 with a complex type.
787
788 GNU CC can allocate complex automatic variables in a noncontiguous
789 fashion; it's even possible for the real part to be in a register while
790 the imaginary part is on the stack (or vice-versa).  None of the
791 supported debugging info formats has a way to represent noncontiguous
792 allocation like this, so GNU CC describes a noncontiguous complex
793 variable as if it were two separate variables of noncomplex type.
794 If the variable's actual name is @code{foo}, the two fictitious
795 variables are named @code{foo$real} and @code{foo$imag}.  You can
796 examine and set these two fictitious variables with your debugger.
797
798 A future version of GDB will know how to recognize such pairs and treat
799 them as a single variable with a complex type.
800
801 @node Hex Floats
802 @section Hex Floats
803 @cindex hex floats
804 GNU CC recognizes floating-point numbers written not only in the usual
805 decimal notation, such as @code{1.55e1}, but also numbers such as
806 @code{0x1.fp3} written in hexadecimal format.  In that format the
807 @code{0x} hex introducer and the @code{p} or @code{P} exponent field are
808 mandatory.  The exponent is a decimal number that indicates the power of
809 2 by which the significand part will be multiplied.  Thus @code{0x1.f} is
810 1 15/16, @code{p3} multiplies it by 8, and the value of @code{0x1.fp3}
811 is the same as @code{1.55e1}.
812
813 Unlike for floating-point numbers in the decimal notation the exponent
814 is always required in the hexadecimal notation.  Otherwise the compiler
815 would not be able to resolve the ambiguity of, e.g., @code{0x1.f}.  This
816 could mean @code{1.0f} or @code{1.9375} since @code{f} is also the
817 extension for floating-point constants of type @code{float}.
818
819 @node Zero Length
820 @section Arrays of Length Zero
821 @cindex arrays of length zero
822 @cindex zero-length arrays
823 @cindex length-zero arrays
824
825 Zero-length arrays are allowed in GNU C.  They are very useful as the last
826 element of a structure which is really a header for a variable-length
827 object:
828
829 @example
830 struct line @{
831   int length;
832   char contents[0];
833 @};
834
835 @{
836   struct line *thisline = (struct line *)
837     malloc (sizeof (struct line) + this_length);
838   thisline->length = this_length;
839 @}
840 @end example
841
842 In standard C, you would have to give @code{contents} a length of 1, which
843 means either you waste space or complicate the argument to @code{malloc}.
844
845 @node Variable Length
846 @section Arrays of Variable Length
847 @cindex variable-length arrays
848 @cindex arrays of variable length
849
850 Variable-length automatic arrays are allowed in GNU C.  These arrays are
851 declared like any other automatic arrays, but with a length that is not
852 a constant expression.  The storage is allocated at the point of
853 declaration and deallocated when the brace-level is exited.  For
854 example:
855
856 @example
857 FILE *
858 concat_fopen (char *s1, char *s2, char *mode)
859 @{
860   char str[strlen (s1) + strlen (s2) + 1];
861   strcpy (str, s1);
862   strcat (str, s2);
863   return fopen (str, mode);
864 @}
865 @end example
866
867 @cindex scope of a variable length array
868 @cindex variable-length array scope
869 @cindex deallocating variable length arrays
870 Jumping or breaking out of the scope of the array name deallocates the
871 storage.  Jumping into the scope is not allowed; you get an error
872 message for it.
873
874 @cindex @code{alloca} vs variable-length arrays
875 You can use the function @code{alloca} to get an effect much like
876 variable-length arrays.  The function @code{alloca} is available in
877 many other C implementations (but not in all).  On the other hand,
878 variable-length arrays are more elegant.
879
880 There are other differences between these two methods.  Space allocated
881 with @code{alloca} exists until the containing @emph{function} returns.
882 The space for a variable-length array is deallocated as soon as the array
883 name's scope ends.  (If you use both variable-length arrays and
884 @code{alloca} in the same function, deallocation of a variable-length array
885 will also deallocate anything more recently allocated with @code{alloca}.)
886
887 You can also use variable-length arrays as arguments to functions:
888
889 @example
890 struct entry
891 tester (int len, char data[len][len])
892 @{
893   @dots{}
894 @}
895 @end example
896
897 The length of an array is computed once when the storage is allocated
898 and is remembered for the scope of the array in case you access it with
899 @code{sizeof}.
900
901 If you want to pass the array first and the length afterward, you can
902 use a forward declaration in the parameter list---another GNU extension.
903
904 @example
905 struct entry
906 tester (int len; char data[len][len], int len)
907 @{
908   @dots{}
909 @}
910 @end example
911
912 @cindex parameter forward declaration
913 The @samp{int len} before the semicolon is a @dfn{parameter forward
914 declaration}, and it serves the purpose of making the name @code{len}
915 known when the declaration of @code{data} is parsed.
916
917 You can write any number of such parameter forward declarations in the
918 parameter list.  They can be separated by commas or semicolons, but the
919 last one must end with a semicolon, which is followed by the ``real''
920 parameter declarations.  Each forward declaration must match a ``real''
921 declaration in parameter name and data type.
922
923 @node Macro Varargs
924 @section Macros with Variable Numbers of Arguments
925 @cindex variable number of arguments
926 @cindex macro with variable arguments
927 @cindex rest argument (in macro)
928
929 In GNU C, a macro can accept a variable number of arguments, much as a
930 function can.  The syntax for defining the macro looks much like that
931 used for a function.  Here is an example:
932
933 @example
934 #define eprintf(format, args...)  \
935  fprintf (stderr, format , ## args)
936 @end example
937
938 Here @code{args} is a @dfn{rest argument}: it takes in zero or more
939 arguments, as many as the call contains.  All of them plus the commas
940 between them form the value of @code{args}, which is substituted into
941 the macro body where @code{args} is used.  Thus, we have this expansion:
942
943 @example
944 eprintf ("%s:%d: ", input_file_name, line_number)
945 @expansion{}
946 fprintf (stderr, "%s:%d: " , input_file_name, line_number)
947 @end example
948
949 @noindent
950 Note that the comma after the string constant comes from the definition
951 of @code{eprintf}, whereas the last comma comes from the value of
952 @code{args}.
953
954 The reason for using @samp{##} is to handle the case when @code{args}
955 matches no arguments at all.  In this case, @code{args} has an empty
956 value.  In this case, the second comma in the definition becomes an
957 embarrassment: if it got through to the expansion of the macro, we would
958 get something like this:
959
960 @example
961 fprintf (stderr, "success!\n" , )
962 @end example
963
964 @noindent
965 which is invalid C syntax.  @samp{##} gets rid of the comma, so we get
966 the following instead:
967
968 @example
969 fprintf (stderr, "success!\n")
970 @end example
971
972 This is a special feature of the GNU C preprocessor: @samp{##} before a
973 rest argument that is empty discards the preceding sequence of
974 non-whitespace characters from the macro definition.  (If another macro
975 argument precedes, none of it is discarded.)
976
977 It might be better to discard the last preprocessor token instead of the
978 last preceding sequence of non-whitespace characters; in fact, we may
979 someday change this feature to do so.  We advise you to write the macro
980 definition so that the preceding sequence of non-whitespace characters
981 is just a single token, so that the meaning will not change if we change
982 the definition of this feature.
983
984 @node Subscripting
985 @section Non-Lvalue Arrays May Have Subscripts
986 @cindex subscripting
987 @cindex arrays, non-lvalue
988
989 @cindex subscripting and function values
990 Subscripting is allowed on arrays that are not lvalues, even though the
991 unary @samp{&} operator is not.  For example, this is valid in GNU C though
992 not valid in other C dialects:
993
994 @example
995 @group
996 struct foo @{int a[4];@};
997
998 struct foo f();
999
1000 bar (int index)
1001 @{
1002   return f().a[index];
1003 @}
1004 @end group
1005 @end example
1006
1007 @node Pointer Arith
1008 @section Arithmetic on @code{void}- and Function-Pointers
1009 @cindex void pointers, arithmetic
1010 @cindex void, size of pointer to
1011 @cindex function pointers, arithmetic
1012 @cindex function, size of pointer to
1013
1014 In GNU C, addition and subtraction operations are supported on pointers to
1015 @code{void} and on pointers to functions.  This is done by treating the
1016 size of a @code{void} or of a function as 1.
1017
1018 A consequence of this is that @code{sizeof} is also allowed on @code{void}
1019 and on function types, and returns 1.
1020
1021 The option @samp{-Wpointer-arith} requests a warning if these extensions
1022 are used.
1023
1024 @node Initializers
1025 @section Non-Constant Initializers
1026 @cindex initializers, non-constant
1027 @cindex non-constant initializers
1028
1029 As in standard C++, the elements of an aggregate initializer for an
1030 automatic variable are not required to be constant expressions in GNU C.
1031 Here is an example of an initializer with run-time varying elements:
1032
1033 @example
1034 foo (float f, float g)
1035 @{
1036   float beat_freqs[2] = @{ f-g, f+g @};
1037   @dots{}
1038 @}
1039 @end example
1040
1041 @node Constructors
1042 @section Constructor Expressions
1043 @cindex constructor expressions
1044 @cindex initializations in expressions
1045 @cindex structures, constructor expression
1046 @cindex expressions, constructor
1047
1048 GNU C supports constructor expressions.  A constructor looks like
1049 a cast containing an initializer.  Its value is an object of the
1050 type specified in the cast, containing the elements specified in
1051 the initializer.
1052
1053 Usually, the specified type is a structure.  Assume that
1054 @code{struct foo} and @code{structure} are declared as shown:
1055
1056 @example
1057 struct foo @{int a; char b[2];@} structure;
1058 @end example
1059
1060 @noindent
1061 Here is an example of constructing a @code{struct foo} with a constructor:
1062
1063 @example
1064 structure = ((struct foo) @{x + y, 'a', 0@});
1065 @end example
1066
1067 @noindent
1068 This is equivalent to writing the following:
1069
1070 @example
1071 @{
1072   struct foo temp = @{x + y, 'a', 0@};
1073   structure = temp;
1074 @}
1075 @end example
1076
1077 You can also construct an array.  If all the elements of the constructor
1078 are (made up of) simple constant expressions, suitable for use in
1079 initializers, then the constructor is an lvalue and can be coerced to a
1080 pointer to its first element, as shown here:
1081
1082 @example
1083 char **foo = (char *[]) @{ "x", "y", "z" @};
1084 @end example
1085
1086 Array constructors whose elements are not simple constants are
1087 not very useful, because the constructor is not an lvalue.  There
1088 are only two valid ways to use it: to subscript it, or initialize
1089 an array variable with it.  The former is probably slower than a
1090 @code{switch} statement, while the latter does the same thing an
1091 ordinary C initializer would do.  Here is an example of
1092 subscripting an array constructor:
1093
1094 @example
1095 output = ((int[]) @{ 2, x, 28 @}) [input];
1096 @end example
1097
1098 Constructor expressions for scalar types and union types are is
1099 also allowed, but then the constructor expression is equivalent
1100 to a cast.
1101
1102 @node Labeled Elements
1103 @section Labeled Elements in Initializers
1104 @cindex initializers with labeled elements
1105 @cindex labeled elements in initializers
1106 @cindex case labels in initializers
1107
1108 Standard C requires the elements of an initializer to appear in a fixed
1109 order, the same as the order of the elements in the array or structure
1110 being initialized.
1111
1112 In GNU C you can give the elements in any order, specifying the array
1113 indices or structure field names they apply to.  This extension is not
1114 implemented in GNU C++.
1115
1116 To specify an array index, write @samp{[@var{index}]} or
1117 @samp{[@var{index}] =} before the element value.  For example,
1118
1119 @example
1120 int a[6] = @{ [4] 29, [2] = 15 @};
1121 @end example
1122
1123 @noindent
1124 is equivalent to
1125
1126 @example
1127 int a[6] = @{ 0, 0, 15, 0, 29, 0 @};
1128 @end example
1129
1130 @noindent
1131 The index values must be constant expressions, even if the array being
1132 initialized is automatic.
1133
1134 To initialize a range of elements to the same value, write
1135 @samp{[@var{first} ... @var{last}] = @var{value}}.  For example,
1136
1137 @example
1138 int widths[] = @{ [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 @};
1139 @end example
1140
1141 @noindent
1142 Note that the length of the array is the highest value specified
1143 plus one.
1144
1145 In a structure initializer, specify the name of a field to initialize
1146 with @samp{@var{fieldname}:} before the element value.  For example,
1147 given the following structure,
1148
1149 @example
1150 struct point @{ int x, y; @};
1151 @end example
1152
1153 @noindent
1154 the following initialization
1155
1156 @example
1157 struct point p = @{ y: yvalue, x: xvalue @};
1158 @end example
1159
1160 @noindent
1161 is equivalent to
1162
1163 @example
1164 struct point p = @{ xvalue, yvalue @};
1165 @end example
1166
1167 Another syntax which has the same meaning is @samp{.@var{fieldname} =}.,
1168 as shown here:
1169
1170 @example
1171 struct point p = @{ .y = yvalue, .x = xvalue @};
1172 @end example
1173
1174 You can also use an element label (with either the colon syntax or the
1175 period-equal syntax) when initializing a union, to specify which element
1176 of the union should be used.  For example,
1177
1178 @example
1179 union foo @{ int i; double d; @};
1180
1181 union foo f = @{ d: 4 @};
1182 @end example
1183
1184 @noindent
1185 will convert 4 to a @code{double} to store it in the union using
1186 the second element.  By contrast, casting 4 to type @code{union foo}
1187 would store it into the union as the integer @code{i}, since it is
1188 an integer.  (@xref{Cast to Union}.)
1189
1190 You can combine this technique of naming elements with ordinary C
1191 initialization of successive elements.  Each initializer element that
1192 does not have a label applies to the next consecutive element of the
1193 array or structure.  For example,
1194
1195 @example
1196 int a[6] = @{ [1] = v1, v2, [4] = v4 @};
1197 @end example
1198
1199 @noindent
1200 is equivalent to
1201
1202 @example
1203 int a[6] = @{ 0, v1, v2, 0, v4, 0 @};
1204 @end example
1205
1206 Labeling the elements of an array initializer is especially useful
1207 when the indices are characters or belong to an @code{enum} type.
1208 For example:
1209
1210 @example
1211 int whitespace[256]
1212   = @{ [' '] = 1, ['\t'] = 1, ['\h'] = 1,
1213       ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 @};
1214 @end example
1215
1216 @node Case Ranges
1217 @section Case Ranges
1218 @cindex case ranges
1219 @cindex ranges in case statements
1220
1221 You can specify a range of consecutive values in a single @code{case} label,
1222 like this:
1223
1224 @example
1225 case @var{low} ... @var{high}:
1226 @end example
1227
1228 @noindent
1229 This has the same effect as the proper number of individual @code{case}
1230 labels, one for each integer value from @var{low} to @var{high}, inclusive.
1231
1232 This feature is especially useful for ranges of ASCII character codes:
1233
1234 @example
1235 case 'A' ... 'Z':
1236 @end example
1237
1238 @strong{Be careful:} Write spaces around the @code{...}, for otherwise
1239 it may be parsed wrong when you use it with integer values.  For example,
1240 write this:
1241
1242 @example
1243 case 1 ... 5:
1244 @end example
1245
1246 @noindent
1247 rather than this:
1248
1249 @example
1250 case 1...5:
1251 @end example
1252
1253 @node Cast to Union
1254 @section Cast to a Union Type
1255 @cindex cast to a union
1256 @cindex union, casting to a
1257
1258 A cast to union type is similar to other casts, except that the type
1259 specified is a union type.  You can specify the type either with
1260 @code{union @var{tag}} or with a typedef name.  A cast to union is actually
1261 a constructor though, not a cast, and hence does not yield an lvalue like
1262 normal casts.  (@xref{Constructors}.)
1263
1264 The types that may be cast to the union type are those of the members
1265 of the union.  Thus, given the following union and variables:
1266
1267 @example
1268 union foo @{ int i; double d; @};
1269 int x;
1270 double y;
1271 @end example
1272
1273 @noindent
1274 both @code{x} and @code{y} can be cast to type @code{union} foo.
1275
1276 Using the cast as the right-hand side of an assignment to a variable of
1277 union type is equivalent to storing in a member of the union:
1278
1279 @example
1280 union foo u;
1281 @dots{}
1282 u = (union foo) x  @equiv{}  u.i = x
1283 u = (union foo) y  @equiv{}  u.d = y
1284 @end example
1285
1286 You can also use the union cast as a function argument:
1287
1288 @example
1289 void hack (union foo);
1290 @dots{}
1291 hack ((union foo) x);
1292 @end example
1293
1294 @node Function Attributes
1295 @section Declaring Attributes of Functions
1296 @cindex function attributes
1297 @cindex declaring attributes of functions
1298 @cindex functions that never return
1299 @cindex functions that have no side effects
1300 @cindex functions in arbitrary sections
1301 @cindex @code{volatile} applied to function
1302 @cindex @code{const} applied to function
1303 @cindex functions with @code{printf}, @code{scanf} or @code{strftime} style arguments
1304 @cindex functions that are passed arguments in registers on the 386
1305 @cindex functions that pop the argument stack on the 386
1306 @cindex functions that do not pop the argument stack on the 386
1307
1308 In GNU C, you declare certain things about functions called in your program
1309 which help the compiler optimize function calls and check your code more
1310 carefully.
1311
1312 The keyword @code{__attribute__} allows you to specify special
1313 attributes when making a declaration.  This keyword is followed by an
1314 attribute specification inside double parentheses.  Nine attributes,
1315 @code{noreturn}, @code{const}, @code{format},
1316 @code{no_instrument_function}, @code{section},
1317 @code{constructor}, @code{destructor}, @code{unused} and @code{weak} are
1318 currently defined for functions.  Other attributes, including
1319 @code{section} are supported for variables declarations (@pxref{Variable
1320 Attributes}) and for types (@pxref{Type Attributes}).
1321
1322 You may also specify attributes with @samp{__} preceding and following
1323 each keyword.  This allows you to use them in header files without
1324 being concerned about a possible macro of the same name.  For example,
1325 you may use @code{__noreturn__} instead of @code{noreturn}.
1326
1327 @table @code
1328 @cindex @code{noreturn} function attribute
1329 @item noreturn
1330 A few standard library functions, such as @code{abort} and @code{exit},
1331 cannot return.  GNU CC knows this automatically.  Some programs define
1332 their own functions that never return.  You can declare them
1333 @code{noreturn} to tell the compiler this fact.  For example,
1334
1335 @smallexample
1336 void fatal () __attribute__ ((noreturn));
1337
1338 void
1339 fatal (@dots{})
1340 @{
1341   @dots{} /* @r{Print error message.} */ @dots{}
1342   exit (1);
1343 @}
1344 @end smallexample
1345
1346 The @code{noreturn} keyword tells the compiler to assume that
1347 @code{fatal} cannot return.  It can then optimize without regard to what
1348 would happen if @code{fatal} ever did return.  This makes slightly
1349 better code.  More importantly, it helps avoid spurious warnings of
1350 uninitialized variables.
1351
1352 Do not assume that registers saved by the calling function are
1353 restored before calling the @code{noreturn} function.
1354
1355 It does not make sense for a @code{noreturn} function to have a return
1356 type other than @code{void}.
1357
1358 The attribute @code{noreturn} is not implemented in GNU C versions
1359 earlier than 2.5.  An alternative way to declare that a function does
1360 not return, which works in the current version and in some older
1361 versions, is as follows:
1362
1363 @smallexample
1364 typedef void voidfn ();
1365
1366 volatile voidfn fatal;
1367 @end smallexample
1368
1369 @cindex @code{const} function attribute
1370 @item const
1371 Many functions do not examine any values except their arguments, and
1372 have no effects except the return value.  Such a function can be subject
1373 to common subexpression elimination and loop optimization just as an
1374 arithmetic operator would be.  These functions should be declared
1375 with the attribute @code{const}.  For example,
1376
1377 @smallexample
1378 int square (int) __attribute__ ((const));
1379 @end smallexample
1380
1381 @noindent
1382 says that the hypothetical function @code{square} is safe to call
1383 fewer times than the program says.
1384
1385 The attribute @code{const} is not implemented in GNU C versions earlier
1386 than 2.5.  An alternative way to declare that a function has no side
1387 effects, which works in the current version and in some older versions,
1388 is as follows:
1389
1390 @smallexample
1391 typedef int intfn ();
1392
1393 extern const intfn square;
1394 @end smallexample
1395
1396 This approach does not work in GNU C++ from 2.6.0 on, since the language
1397 specifies that the @samp{const} must be attached to the return value.
1398
1399 @cindex pointer arguments
1400 Note that a function that has pointer arguments and examines the data
1401 pointed to must @emph{not} be declared @code{const}.  Likewise, a
1402 function that calls a non-@code{const} function usually must not be
1403 @code{const}.  It does not make sense for a @code{const} function to
1404 return @code{void}.
1405
1406 @item format (@var{archetype}, @var{string-index}, @var{first-to-check})
1407 @cindex @code{format} function attribute
1408 The @code{format} attribute specifies that a function takes @code{printf},
1409 @code{scanf}, or @code{strftime} style arguments which should be type-checked
1410 against a format string.  For example, the declaration:
1411
1412 @smallexample
1413 extern int
1414 my_printf (void *my_object, const char *my_format, ...)
1415       __attribute__ ((format (printf, 2, 3)));
1416 @end smallexample
1417
1418 @noindent
1419 causes the compiler to check the arguments in calls to @code{my_printf}
1420 for consistency with the @code{printf} style format string argument
1421 @code{my_format}.
1422
1423 The parameter @var{archetype} determines how the format string is
1424 interpreted, and should be either @code{printf}, @code{printf0}, @code{scanf},
1425 or @code{strftime}.  @code{printf0} allows the format string to be a null
1426 pointer, while @code{printf} does not.  The
1427 parameter @var{string-index} specifies which argument is the format
1428 string argument (starting from 1), while @var{first-to-check} is the
1429 number of the first argument to check against the format string.  For
1430 functions where the arguments are not available to be checked (such as
1431 @code{vprintf}), specify the third parameter as zero.  In this case the
1432 compiler only checks the format string for consistency.
1433
1434 In the example above, the format string (@code{my_format}) is the second
1435 argument of the function @code{my_print}, and the arguments to check
1436 start with the third argument, so the correct parameters for the format
1437 attribute are 2 and 3.
1438
1439 The @code{format} attribute allows you to identify your own functions
1440 which take format strings as arguments, so that GNU CC can check the
1441 calls to these functions for errors.  The compiler always checks formats
1442 for the ANSI library functions @code{printf}, @code{fprintf},
1443 @code{sprintf}, @code{scanf}, @code{fscanf}, @code{sscanf}, @code{strftime},
1444 @code{vprintf}, @code{vfprintf} and @code{vsprintf} whenever such
1445 warnings are requested (using @samp{-Wformat}), so there is no need to
1446 modify the header file @file{stdio.h}.
1447
1448 @item format_arg (@var{string-index})
1449 @cindex @code{format_arg} function attribute
1450 The @code{format_arg} attribute specifies that a function takes
1451 @code{printf} or @code{scanf} style arguments, modifies it (for example,
1452 to translate it into another language), and passes it to a @code{printf}
1453 or @code{scanf} style function.  For example, the declaration:
1454
1455 @smallexample
1456 extern char *
1457 my_dgettext (char *my_domain, const char *my_format)
1458       __attribute__ ((format_arg (2)));
1459 @end smallexample
1460
1461 @noindent
1462 causes the compiler to check the arguments in calls to
1463 @code{my_dgettext} whose result is passed to a @code{printf},
1464 @code{scanf}, or @code{strftime} type function for consistency with the
1465 @code{printf} style format string argument @code{my_format}.
1466
1467 The parameter @var{string-index} specifies which argument is the format
1468 string argument (starting from 1).
1469
1470 The @code{format-arg} attribute allows you to identify your own
1471 functions which modify format strings, so that GNU CC can check the
1472 calls to @code{printf}, @code{scanf}, or @code{strftime} function whose
1473 operands are a call to one of your own function.  The compiler always
1474 treats @code{gettext}, @code{dgettext}, and @code{dcgettext} in this
1475 manner.
1476
1477 @item no_instrument_function
1478 @cindex @code{no_instrument_function} function attribute
1479 If @samp{-finstrument-functions} is given, profiling function calls will
1480 be generated at entry and exit of most user-compiled functions.
1481 Functions with this attribute will not be so instrumented.
1482
1483 @item section ("section-name")
1484 @cindex @code{section} function attribute
1485 Normally, the compiler places the code it generates in the @code{text} section.
1486 Sometimes, however, you need additional sections, or you need certain
1487 particular functions to appear in special sections.  The @code{section}
1488 attribute specifies that a function lives in a particular section.
1489 For example, the declaration:
1490
1491 @smallexample
1492 extern void foobar (void) __attribute__ ((section ("bar")));
1493 @end smallexample
1494
1495 @noindent
1496 puts the function @code{foobar} in the @code{bar} section.
1497
1498 Some file formats do not support arbitrary sections so the @code{section}
1499 attribute is not available on all platforms.
1500 If you need to map the entire contents of a module to a particular
1501 section, consider using the facilities of the linker instead.
1502
1503 @item constructor
1504 @itemx destructor
1505 @cindex @code{constructor} function attribute
1506 @cindex @code{destructor} function attribute
1507 The @code{constructor} attribute causes the function to be called
1508 automatically before execution enters @code{main ()}.  Similarly, the
1509 @code{destructor} attribute causes the function to be called
1510 automatically after @code{main ()} has completed or @code{exit ()} has
1511 been called.  Functions with these attributes are useful for
1512 initializing data that will be used implicitly during the execution of
1513 the program.
1514
1515 These attributes are not currently implemented for Objective C.
1516
1517 @item unused
1518 This attribute, attached to a function, means that the function is meant
1519 to be possibly unused.  GNU CC will not produce a warning for this
1520 function.  GNU C++ does not currently support this attribute as
1521 definitions without parameters are valid in C++.
1522
1523 @item weak
1524 @cindex @code{weak} attribute
1525 The @code{weak} attribute causes the declaration to be emitted as a weak
1526 symbol rather than a global.  This is primarily useful in defining
1527 library functions which can be overridden in user code, though it can
1528 also be used with non-function declarations.  Weak symbols are supported
1529 for ELF targets, and also for a.out targets when using the GNU assembler
1530 and linker.
1531
1532 @item alias ("target")
1533 @cindex @code{alias} attribute
1534 The @code{alias} attribute causes the declaration to be emitted as an
1535 alias for another symbol, which must be specified.  For instance,
1536
1537 @smallexample
1538 void __f () @{ /* do something */; @}
1539 void f () __attribute__ ((weak, alias ("__f")));
1540 @end smallexample
1541
1542 declares @samp{f} to be a weak alias for @samp{__f}.  In C++, the
1543 mangled name for the target must be used.
1544
1545 Not all target machines support this attribute.
1546
1547 @item no_check_memory_usage
1548 @cindex @code{no_check_memory_usage} function attribute
1549 If @samp{-fcheck-memory-usage} is given, calls to support routines will
1550 be generated before most memory accesses, to permit support code to
1551 record usage and detect uses of uninitialized or unallocated storage.
1552 Since the compiler cannot handle them properly, @code{asm} statements
1553 are not allowed.  Declaring a function with this attribute disables the
1554 memory checking code for that function, permitting the use of @code{asm}
1555 statements without requiring separate compilation with different
1556 options, and allowing you to write support routines of your own if you
1557 wish, without getting infinite recursion if they get compiled with this
1558 option.
1559
1560 @item regparm (@var{number})
1561 @cindex functions that are passed arguments in registers on the 386
1562 On the Intel 386, the @code{regparm} attribute causes the compiler to
1563 pass up to @var{number} integer arguments in registers @var{EAX},
1564 @var{EDX}, and @var{ECX} instead of on the stack.  Functions that take a
1565 variable number of arguments will continue to be passed all of their
1566 arguments on the stack.
1567
1568 @item stdcall
1569 @cindex functions that pop the argument stack on the 386
1570 On the Intel 386, the @code{stdcall} attribute causes the compiler to
1571 assume that the called function will pop off the stack space used to
1572 pass arguments, unless it takes a variable number of arguments.
1573
1574 The PowerPC compiler for Windows NT currently ignores the @code{stdcall}
1575 attribute.
1576
1577 @item cdecl
1578 @cindex functions that do pop the argument stack on the 386
1579 On the Intel 386, the @code{cdecl} attribute causes the compiler to
1580 assume that the calling function will pop off the stack space used to
1581 pass arguments.  This is
1582 useful to override the effects of the @samp{-mrtd} switch.
1583
1584 The PowerPC compiler for Windows NT currently ignores the @code{cdecl}
1585 attribute.
1586
1587 @item longcall
1588 @cindex functions called via pointer on the RS/6000 and PowerPC
1589 On the RS/6000 and PowerPC, the @code{longcall} attribute causes the
1590 compiler to always call the function via a pointer, so that functions
1591 which reside further than 64 megabytes (67,108,864 bytes) from the
1592 current location can be called.
1593
1594 @item dllimport
1595 @cindex functions which are imported from a dll on PowerPC Windows NT
1596 On the PowerPC running Windows NT, the @code{dllimport} attribute causes
1597 the compiler to call the function via a global pointer to the function
1598 pointer that is set up by the Windows NT dll library.  The pointer name
1599 is formed by combining @code{__imp_} and the function name.
1600
1601 @item dllexport
1602 @cindex functions which are exported from a dll on PowerPC Windows NT
1603 On the PowerPC running Windows NT, the @code{dllexport} attribute causes
1604 the compiler to provide a global pointer to the function pointer, so
1605 that it can be called with the @code{dllimport} attribute.  The pointer
1606 name is formed by combining @code{__imp_} and the function name.
1607
1608 @item exception (@var{except-func} [, @var{except-arg}])
1609 @cindex functions which specify exception handling on PowerPC Windows NT
1610 On the PowerPC running Windows NT, the @code{exception} attribute causes
1611 the compiler to modify the structured exception table entry it emits for
1612 the declared function.  The string or identifier @var{except-func} is
1613 placed in the third entry of the structured exception table.  It
1614 represents a function, which is called by the exception handling
1615 mechanism if an exception occurs.  If it was specified, the string or
1616 identifier @var{except-arg} is placed in the fourth entry of the
1617 structured exception table.
1618
1619 @item function_vector
1620 @cindex calling functions through the function vector on the H8/300 processors
1621 Use this option on the H8/300 and H8/300H to indicate that the specified
1622 function should be called through the function vector.  Calling a
1623 function through the function vector will reduce code size, however;
1624 the function vector has a limited size (maximum 128 entries on the H8/300
1625 and 64 entries on the H8/300H) and shares space with the interrupt vector.
1626
1627 You must use GAS and GLD from GNU binutils version 2.7 or later for
1628 this option to work correctly.
1629
1630 @item interrupt_handler
1631 @cindex interrupt handler functions on the H8/300 processors
1632 Use this option on the H8/300 and H8/300H to indicate that the specified
1633 function is an interrupt handler.  The compiler will generate function
1634 entry and exit sequences suitable for use in an interrupt handler when this
1635 attribute is present.
1636
1637 @item eightbit_data
1638 @cindex eight bit data on the H8/300 and H8/300H
1639 Use this option on the H8/300 and H8/300H to indicate that the specified
1640 variable should be placed into the eight bit data section.
1641 The compiler will generate more efficient code for certain operations
1642 on data in the eight bit data area.  Note the eight bit data area is limited to
1643 256 bytes of data.
1644
1645 You must use GAS and GLD from GNU binutils version 2.7 or later for
1646 this option to work correctly.
1647
1648 @item tiny_data
1649 @cindex tiny data section on the H8/300H
1650 Use this option on the H8/300H to indicate that the specified
1651 variable should be placed into the tiny data section.
1652 The compiler will generate more efficient code for loads and stores
1653 on data in the tiny data section.  Note the tiny data area is limited to
1654 slightly under 32kbytes of data.
1655
1656 @item interrupt
1657 @cindex interrupt handlers on the M32R/D
1658 Use this option on the M32R/D to indicate that the specified
1659 function is an interrupt handler.  The compiler will generate function
1660 entry and exit sequences suitable for use in an interrupt handler when this
1661 attribute is present.
1662
1663 @item model (@var{model-name})
1664 @cindex function addressability on the M32R/D
1665 Use this attribute on the M32R/D to set the addressability of an object,
1666 and the code generated for a function.
1667 The identifier @var{model-name} is one of @code{small}, @code{medium},
1668 or @code{large}, representing each of the code models.
1669
1670 Small model objects live in the lower 16MB of memory (so that their
1671 addresses can be loaded with the @code{ld24} instruction), and are
1672 callable with the @code{bl} instruction.
1673
1674 Medium model objects may live anywhere in the 32 bit address space (the
1675 compiler will generate @code{seth/add3} instructions to load their addresses),
1676 and are callable with the @code{bl} instruction.
1677
1678 Large model objects may live anywhere in the 32 bit address space (the
1679 compiler will generate @code{seth/add3} instructions to load their addresses),
1680 and may not be reachable with the @code{bl} instruction (the compiler will
1681 generate the much slower @code{seth/add3/jl} instruction sequence).
1682
1683 @end table
1684
1685 You can specify multiple attributes in a declaration by separating them
1686 by commas within the double parentheses or by immediately following an
1687 attribute declaration with another attribute declaration.
1688
1689 @cindex @code{#pragma}, reason for not using
1690 @cindex pragma, reason for not using
1691 Some people object to the @code{__attribute__} feature, suggesting that ANSI C's
1692 @code{#pragma} should be used instead.  There are two reasons for not
1693 doing this.
1694
1695 @enumerate
1696 @item
1697 It is impossible to generate @code{#pragma} commands from a macro.
1698
1699 @item
1700 There is no telling what the same @code{#pragma} might mean in another
1701 compiler.
1702 @end enumerate
1703
1704 These two reasons apply to almost any application that might be proposed
1705 for @code{#pragma}.  It is basically a mistake to use @code{#pragma} for
1706 @emph{anything}.
1707
1708 @node Function Prototypes
1709 @section Prototypes and Old-Style Function Definitions
1710 @cindex function prototype declarations
1711 @cindex old-style function definitions
1712 @cindex promotion of formal parameters
1713
1714 GNU C extends ANSI C to allow a function prototype to override a later
1715 old-style non-prototype definition.  Consider the following example:
1716
1717 @example
1718 /* @r{Use prototypes unless the compiler is old-fashioned.}  */
1719 #ifdef __STDC__
1720 #define P(x) x
1721 #else
1722 #define P(x) ()
1723 #endif
1724
1725 /* @r{Prototype function declaration.}  */
1726 int isroot P((uid_t));
1727
1728 /* @r{Old-style function definition.}  */
1729 int
1730 isroot (x)   /* ??? lossage here ??? */
1731      uid_t x;
1732 @{
1733   return x == 0;
1734 @}
1735 @end example
1736
1737 Suppose the type @code{uid_t} happens to be @code{short}.  ANSI C does
1738 not allow this example, because subword arguments in old-style
1739 non-prototype definitions are promoted.  Therefore in this example the
1740 function definition's argument is really an @code{int}, which does not
1741 match the prototype argument type of @code{short}.
1742
1743 This restriction of ANSI C makes it hard to write code that is portable
1744 to traditional C compilers, because the programmer does not know
1745 whether the @code{uid_t} type is @code{short}, @code{int}, or
1746 @code{long}.  Therefore, in cases like these GNU C allows a prototype
1747 to override a later old-style definition.  More precisely, in GNU C, a
1748 function prototype argument type overrides the argument type specified
1749 by a later old-style definition if the former type is the same as the
1750 latter type before promotion.  Thus in GNU C the above example is
1751 equivalent to the following:
1752
1753 @example
1754 int isroot (uid_t);
1755
1756 int
1757 isroot (uid_t x)
1758 @{
1759   return x == 0;
1760 @}
1761 @end example
1762
1763 GNU C++ does not support old-style function definitions, so this
1764 extension is irrelevant.
1765
1766 @node C++ Comments
1767 @section C++ Style Comments
1768 @cindex //
1769 @cindex C++ comments
1770 @cindex comments, C++ style
1771
1772 In GNU C, you may use C++ style comments, which start with @samp{//} and
1773 continue until the end of the line.  Many other C implementations allow
1774 such comments, and they are likely to be in a future C standard.
1775 However, C++ style comments are not recognized if you specify
1776 @w{@samp{-ansi}} or @w{@samp{-traditional}}, since they are incompatible
1777 with traditional constructs like @code{dividend//*comment*/divisor}.
1778
1779 @node Dollar Signs
1780 @section Dollar Signs in Identifier Names
1781 @cindex $
1782 @cindex dollar signs in identifier names
1783 @cindex identifier names, dollar signs in
1784
1785 In GNU C, you may normally use dollar signs in identifier names.
1786 This is because many traditional C implementations allow such identifiers.
1787 However, dollar signs in identifiers are not supported on a few target
1788 machines, typically because the target assembler does not allow them.
1789
1790 @node Character Escapes
1791 @section The Character @key{ESC} in Constants
1792
1793 You can use the sequence @samp{\e} in a string or character constant to
1794 stand for the ASCII character @key{ESC}.
1795
1796 @node Alignment
1797 @section Inquiring on Alignment of Types or Variables
1798 @cindex alignment
1799 @cindex type alignment
1800 @cindex variable alignment
1801
1802 The keyword @code{__alignof__} allows you to inquire about how an object
1803 is aligned, or the minimum alignment usually required by a type.  Its
1804 syntax is just like @code{sizeof}.
1805
1806 For example, if the target machine requires a @code{double} value to be
1807 aligned on an 8-byte boundary, then @code{__alignof__ (double)} is 8.
1808 This is true on many RISC machines.  On more traditional machine
1809 designs, @code{__alignof__ (double)} is 4 or even 2.
1810
1811 Some machines never actually require alignment; they allow reference to any
1812 data type even at an odd addresses.  For these machines, @code{__alignof__}
1813 reports the @emph{recommended} alignment of a type.
1814
1815 When the operand of @code{__alignof__} is an lvalue rather than a type, the
1816 value is the largest alignment that the lvalue is known to have.  It may
1817 have this alignment as a result of its data type, or because it is part of
1818 a structure and inherits alignment from that structure.  For example, after
1819 this declaration:
1820
1821 @example
1822 struct foo @{ int x; char y; @} foo1;
1823 @end example
1824
1825 @noindent
1826 the value of @code{__alignof__ (foo1.y)} is probably 2 or 4, the same as
1827 @code{__alignof__ (int)}, even though the data type of @code{foo1.y}
1828 does not itself demand any alignment.@refill
1829
1830 A related feature which lets you specify the alignment of an object is
1831 @code{__attribute__ ((aligned (@var{alignment})))}; see the following
1832 section.
1833
1834 @node Variable Attributes
1835 @section Specifying Attributes of Variables
1836 @cindex attribute of variables
1837 @cindex variable attributes
1838
1839 The keyword @code{__attribute__} allows you to specify special
1840 attributes of variables or structure fields.  This keyword is followed
1841 by an attribute specification inside double parentheses.  Eight
1842 attributes are currently defined for variables: @code{aligned},
1843 @code{mode}, @code{nocommon}, @code{packed}, @code{section},
1844 @code{transparent_union}, @code{unused}, and @code{weak}.  Other
1845 attributes are available for functions (@pxref{Function Attributes}) and
1846 for types (@pxref{Type Attributes}).
1847
1848 You may also specify attributes with @samp{__} preceding and following
1849 each keyword.  This allows you to use them in header files without
1850 being concerned about a possible macro of the same name.  For example,
1851 you may use @code{__aligned__} instead of @code{aligned}.
1852
1853 @table @code
1854 @cindex @code{aligned} attribute
1855 @item aligned (@var{alignment})
1856 This attribute specifies a minimum alignment for the variable or
1857 structure field, measured in bytes.  For example, the declaration:
1858
1859 @smallexample
1860 int x __attribute__ ((aligned (16))) = 0;
1861 @end smallexample
1862
1863 @noindent
1864 causes the compiler to allocate the global variable @code{x} on a
1865 16-byte boundary.  On a 68040, this could be used in conjunction with
1866 an @code{asm} expression to access the @code{move16} instruction which
1867 requires 16-byte aligned operands.
1868
1869 You can also specify the alignment of structure fields.  For example, to
1870 create a double-word aligned @code{int} pair, you could write:
1871
1872 @smallexample
1873 struct foo @{ int x[2] __attribute__ ((aligned (8))); @};
1874 @end smallexample
1875
1876 @noindent
1877 This is an alternative to creating a union with a @code{double} member
1878 that forces the union to be double-word aligned.
1879
1880 It is not possible to specify the alignment of functions; the alignment
1881 of functions is determined by the machine's requirements and cannot be
1882 changed.  You cannot specify alignment for a typedef name because such a
1883 name is just an alias, not a distinct type.
1884
1885 As in the preceding examples, you can explicitly specify the alignment
1886 (in bytes) that you wish the compiler to use for a given variable or
1887 structure field.  Alternatively, you can leave out the alignment factor
1888 and just ask the compiler to align a variable or field to the maximum
1889 useful alignment for the target machine you are compiling for.  For
1890 example, you could write:
1891
1892 @smallexample
1893 short array[3] __attribute__ ((aligned));
1894 @end smallexample
1895
1896 Whenever you leave out the alignment factor in an @code{aligned} attribute
1897 specification, the compiler automatically sets the alignment for the declared
1898 variable or field to the largest alignment which is ever used for any data
1899 type on the target machine you are compiling for.  Doing this can often make
1900 copy operations more efficient, because the compiler can use whatever
1901 instructions copy the biggest chunks of memory when performing copies to
1902 or from the variables or fields that you have aligned this way.
1903
1904 The @code{aligned} attribute can only increase the alignment; but you
1905 can decrease it by specifying @code{packed} as well.  See below.
1906
1907 Note that the effectiveness of @code{aligned} attributes may be limited
1908 by inherent limitations in your linker.  On many systems, the linker is
1909 only able to arrange for variables to be aligned up to a certain maximum
1910 alignment.  (For some linkers, the maximum supported alignment may
1911 be very very small.)  If your linker is only able to align variables
1912 up to a maximum of 8 byte alignment, then specifying @code{aligned(16)}
1913 in an @code{__attribute__} will still only provide you with 8 byte
1914 alignment.  See your linker documentation for further information.
1915
1916 @item mode (@var{mode})
1917 @cindex @code{mode} attribute
1918 This attribute specifies the data type for the declaration---whichever
1919 type corresponds to the mode @var{mode}.  This in effect lets you
1920 request an integer or floating point type according to its width.
1921
1922 You may also specify a mode of @samp{byte} or @samp{__byte__} to
1923 indicate the mode corresponding to a one-byte integer, @samp{word} or
1924 @samp{__word__} for the mode of a one-word integer, and @samp{pointer}
1925 or @samp{__pointer__} for the mode used to represent pointers.
1926
1927 @item nocommon
1928 @cindex @code{nocommon} attribute
1929 This attribute specifies requests GNU CC not to place a variable
1930 ``common'' but instead to allocate space for it directly.  If you
1931 specify the @samp{-fno-common} flag, GNU CC will do this for all
1932 variables.
1933
1934 Specifying the @code{nocommon} attribute for a variable provides an
1935 initialization of zeros.  A variable may only be initialized in one
1936 source file.
1937
1938 @item packed
1939 @cindex @code{packed} attribute
1940 The @code{packed} attribute specifies that a variable or structure field
1941 should have the smallest possible alignment---one byte for a variable,
1942 and one bit for a field, unless you specify a larger value with the
1943 @code{aligned} attribute.
1944
1945 Here is a structure in which the field @code{x} is packed, so that it
1946 immediately follows @code{a}:
1947
1948 @example
1949 struct foo
1950 @{
1951   char a;
1952   int x[2] __attribute__ ((packed));
1953 @};
1954 @end example
1955
1956 @item section ("section-name")
1957 @cindex @code{section} variable attribute
1958 Normally, the compiler places the objects it generates in sections like
1959 @code{data} and @code{bss}.  Sometimes, however, you need additional sections,
1960 or you need certain particular variables to appear in special sections,
1961 for example to map to special hardware.  The @code{section}
1962 attribute specifies that a variable (or function) lives in a particular
1963 section.  For example, this small program uses several specific section names:
1964
1965 @smallexample
1966 struct duart a __attribute__ ((section ("DUART_A"))) = @{ 0 @};
1967 struct duart b __attribute__ ((section ("DUART_B"))) = @{ 0 @};
1968 char stack[10000] __attribute__ ((section ("STACK"))) = @{ 0 @};
1969 int init_data __attribute__ ((section ("INITDATA"))) = 0;
1970
1971 main()
1972 @{
1973   /* Initialize stack pointer */
1974   init_sp (stack + sizeof (stack));
1975
1976   /* Initialize initialized data */
1977   memcpy (&init_data, &data, &edata - &data);
1978
1979   /* Turn on the serial ports */
1980   init_duart (&a);
1981   init_duart (&b);
1982 @}
1983 @end smallexample
1984
1985 @noindent
1986 Use the @code{section} attribute with an @emph{initialized} definition
1987 of a @emph{global} variable, as shown in the example.  GNU CC issues
1988 a warning and otherwise ignores the @code{section} attribute in
1989 uninitialized variable declarations.
1990
1991 You may only use the @code{section} attribute with a fully initialized
1992 global definition because of the way linkers work.  The linker requires
1993 each object be defined once, with the exception that uninitialized
1994 variables tentatively go in the @code{common} (or @code{bss}) section
1995 and can be multiply "defined".  You can force a variable to be
1996 initialized with the @samp{-fno-common} flag or the @code{nocommon}
1997 attribute.
1998
1999 Some file formats do not support arbitrary sections so the @code{section}
2000 attribute is not available on all platforms.
2001 If you need to map the entire contents of a module to a particular
2002 section, consider using the facilities of the linker instead.
2003
2004 @item transparent_union
2005 This attribute, attached to a function parameter which is a union, means
2006 that the corresponding argument may have the type of any union member,
2007 but the argument is passed as if its type were that of the first union
2008 member.  For more details see @xref{Type Attributes}.  You can also use
2009 this attribute on a @code{typedef} for a union data type; then it
2010 applies to all function parameters with that type.
2011
2012 @item unused
2013 This attribute, attached to a variable, means that the variable is meant
2014 to be possibly unused.  GNU CC will not produce a warning for this
2015 variable.
2016
2017 @item weak
2018 The @code{weak} attribute is described in @xref{Function Attributes}.
2019
2020 @item model (@var{model-name})
2021 @cindex variable addressability on the M32R/D
2022 Use this attribute on the M32R/D to set the addressability of an object.
2023 The identifier @var{model-name} is one of @code{small}, @code{medium},
2024 or @code{large}, representing each of the code models.
2025
2026 Small model objects live in the lower 16MB of memory (so that their
2027 addresses can be loaded with the @code{ld24} instruction).
2028
2029 Medium and large model objects may live anywhere in the 32 bit address space
2030 (the compiler will generate @code{seth/add3} instructions to load their
2031 addresses).
2032
2033 @end table
2034
2035 To specify multiple attributes, separate them by commas within the
2036 double parentheses: for example, @samp{__attribute__ ((aligned (16),
2037 packed))}.
2038
2039 @node Type Attributes
2040 @section Specifying Attributes of Types
2041 @cindex attribute of types
2042 @cindex type attributes
2043
2044 The keyword @code{__attribute__} allows you to specify special
2045 attributes of @code{struct} and @code{union} types when you define such
2046 types.  This keyword is followed by an attribute specification inside
2047 double parentheses.  Three attributes are currently defined for types:
2048 @code{aligned}, @code{packed}, and @code{transparent_union}.  Other
2049 attributes are defined for functions (@pxref{Function Attributes}) and
2050 for variables (@pxref{Variable Attributes}).
2051
2052 You may also specify any one of these attributes with @samp{__}
2053 preceding and following its keyword.  This allows you to use these
2054 attributes in header files without being concerned about a possible
2055 macro of the same name.  For example, you may use @code{__aligned__}
2056 instead of @code{aligned}.
2057
2058 You may specify the @code{aligned} and @code{transparent_union}
2059 attributes either in a @code{typedef} declaration or just past the
2060 closing curly brace of a complete enum, struct or union type
2061 @emph{definition} and the @code{packed} attribute only past the closing
2062 brace of a definition.
2063
2064 You may also specify attributes between the enum, struct or union
2065 tag and the name of the type rather than after the closing brace.
2066
2067 @table @code
2068 @cindex @code{aligned} attribute
2069 @item aligned (@var{alignment})
2070 This attribute specifies a minimum alignment (in bytes) for variables
2071 of the specified type.  For example, the declarations:
2072
2073 @smallexample
2074 struct S @{ short f[3]; @} __attribute__ ((aligned (8)));
2075 typedef int more_aligned_int __attribute__ ((aligned (8)));
2076 @end smallexample
2077
2078 @noindent
2079 force the compiler to insure (as far as it can) that each variable whose
2080 type is @code{struct S} or @code{more_aligned_int} will be allocated and
2081 aligned @emph{at least} on a 8-byte boundary.  On a Sparc, having all
2082 variables of type @code{struct S} aligned to 8-byte boundaries allows
2083 the compiler to use the @code{ldd} and @code{std} (doubleword load and
2084 store) instructions when copying one variable of type @code{struct S} to
2085 another, thus improving run-time efficiency.
2086
2087 Note that the alignment of any given @code{struct} or @code{union} type
2088 is required by the ANSI C standard to be at least a perfect multiple of
2089 the lowest common multiple of the alignments of all of the members of
2090 the @code{struct} or @code{union} in question.  This means that you @emph{can}
2091 effectively adjust the alignment of a @code{struct} or @code{union}
2092 type by attaching an @code{aligned} attribute to any one of the members
2093 of such a type, but the notation illustrated in the example above is a
2094 more obvious, intuitive, and readable way to request the compiler to
2095 adjust the alignment of an entire @code{struct} or @code{union} type.
2096
2097 As in the preceding example, you can explicitly specify the alignment
2098 (in bytes) that you wish the compiler to use for a given @code{struct}
2099 or @code{union} type.  Alternatively, you can leave out the alignment factor
2100 and just ask the compiler to align a type to the maximum
2101 useful alignment for the target machine you are compiling for.  For
2102 example, you could write:
2103
2104 @smallexample
2105 struct S @{ short f[3]; @} __attribute__ ((aligned));
2106 @end smallexample
2107
2108 Whenever you leave out the alignment factor in an @code{aligned}
2109 attribute specification, the compiler automatically sets the alignment
2110 for the type to the largest alignment which is ever used for any data
2111 type on the target machine you are compiling for.  Doing this can often
2112 make copy operations more efficient, because the compiler can use
2113 whatever instructions copy the biggest chunks of memory when performing
2114 copies to or from the variables which have types that you have aligned
2115 this way.
2116
2117 In the example above, if the size of each @code{short} is 2 bytes, then
2118 the size of the entire @code{struct S} type is 6 bytes.  The smallest
2119 power of two which is greater than or equal to that is 8, so the
2120 compiler sets the alignment for the entire @code{struct S} type to 8
2121 bytes.
2122
2123 Note that although you can ask the compiler to select a time-efficient
2124 alignment for a given type and then declare only individual stand-alone
2125 objects of that type, the compiler's ability to select a time-efficient
2126 alignment is primarily useful only when you plan to create arrays of
2127 variables having the relevant (efficiently aligned) type.  If you
2128 declare or use arrays of variables of an efficiently-aligned type, then
2129 it is likely that your program will also be doing pointer arithmetic (or
2130 subscripting, which amounts to the same thing) on pointers to the
2131 relevant type, and the code that the compiler generates for these
2132 pointer arithmetic operations will often be more efficient for
2133 efficiently-aligned types than for other types.
2134
2135 The @code{aligned} attribute can only increase the alignment; but you
2136 can decrease it by specifying @code{packed} as well.  See below.
2137
2138 Note that the effectiveness of @code{aligned} attributes may be limited
2139 by inherent limitations in your linker.  On many systems, the linker is
2140 only able to arrange for variables to be aligned up to a certain maximum
2141 alignment.  (For some linkers, the maximum supported alignment may
2142 be very very small.)  If your linker is only able to align variables
2143 up to a maximum of 8 byte alignment, then specifying @code{aligned(16)}
2144 in an @code{__attribute__} will still only provide you with 8 byte
2145 alignment.  See your linker documentation for further information.
2146
2147 @item packed
2148 This attribute, attached to an @code{enum}, @code{struct}, or
2149 @code{union} type definition, specified that the minimum required memory
2150 be used to represent the type.
2151
2152 Specifying this attribute for @code{struct} and @code{union} types is
2153 equivalent to specifying the @code{packed} attribute on each of the
2154 structure or union members.  Specifying the @samp{-fshort-enums}
2155 flag on the line is equivalent to specifying the @code{packed}
2156 attribute on all @code{enum} definitions.
2157
2158 You may only specify this attribute after a closing curly brace on an
2159 @code{enum} definition, not in a @code{typedef} declaration, unless that
2160 declaration also contains the definition of the @code{enum}.
2161
2162 @item transparent_union
2163 This attribute, attached to a @code{union} type definition, indicates
2164 that any function parameter having that union type causes calls to that
2165 function to be treated in a special way.
2166
2167 First, the argument corresponding to a transparent union type can be of
2168 any type in the union; no cast is required.  Also, if the union contains
2169 a pointer type, the corresponding argument can be a null pointer
2170 constant or a void pointer expression; and if the union contains a void
2171 pointer type, the corresponding argument can be any pointer expression.
2172 If the union member type is a pointer, qualifiers like @code{const} on
2173 the referenced type must be respected, just as with normal pointer
2174 conversions.
2175
2176 Second, the argument is passed to the function using the calling
2177 conventions of first member of the transparent union, not the calling
2178 conventions of the union itself.  All members of the union must have the
2179 same machine representation; this is necessary for this argument passing
2180 to work properly.
2181
2182 Transparent unions are designed for library functions that have multiple
2183 interfaces for compatibility reasons.  For example, suppose the
2184 @code{wait} function must accept either a value of type @code{int *} to
2185 comply with Posix, or a value of type @code{union wait *} to comply with
2186 the 4.1BSD interface.  If @code{wait}'s parameter were @code{void *},
2187 @code{wait} would accept both kinds of arguments, but it would also
2188 accept any other pointer type and this would make argument type checking
2189 less useful.  Instead, @code{<sys/wait.h>} might define the interface
2190 as follows:
2191
2192 @smallexample
2193 typedef union
2194   @{
2195     int *__ip;
2196     union wait *__up;
2197   @} wait_status_ptr_t __attribute__ ((__transparent_union__));
2198
2199 pid_t wait (wait_status_ptr_t);
2200 @end smallexample
2201
2202 This interface allows either @code{int *} or @code{union wait *}
2203 arguments to be passed, using the @code{int *} calling convention.
2204 The program can call @code{wait} with arguments of either type:
2205
2206 @example
2207 int w1 () @{ int w; return wait (&w); @}
2208 int w2 () @{ union wait w; return wait (&w); @}
2209 @end example
2210
2211 With this interface, @code{wait}'s implementation might look like this:
2212
2213 @example
2214 pid_t wait (wait_status_ptr_t p)
2215 @{
2216   return waitpid (-1, p.__ip, 0);
2217 @}
2218 @end example
2219
2220 @item unused
2221 When attached to a type (including a @code{union} or a @code{struct}),
2222 this attribute means that variables of that type are meant to appear
2223 possibly unused.  GNU CC will not produce a warning for any variables of
2224 that type, even if the variable appears to do nothing.  This is often
2225 the case with lock or thread classes, which are usually defined and then
2226 not referenced, but contain constructors and destructors that have
2227 nontrivial bookkeeping functions.
2228
2229 @end table
2230
2231 To specify multiple attributes, separate them by commas within the
2232 double parentheses: for example, @samp{__attribute__ ((aligned (16),
2233 packed))}.
2234
2235 @node Inline
2236 @section An Inline Function is As Fast As a Macro
2237 @cindex inline functions
2238 @cindex integrating function code
2239 @cindex open coding
2240 @cindex macros, inline alternative
2241
2242 By declaring a function @code{inline}, you can direct GNU CC to
2243 integrate that function's code into the code for its callers.  This
2244 makes execution faster by eliminating the function-call overhead; in
2245 addition, if any of the actual argument values are constant, their known
2246 values may permit simplifications at compile time so that not all of the
2247 inline function's code needs to be included.  The effect on code size is
2248 less predictable; object code may be larger or smaller with function
2249 inlining, depending on the particular case.  Inlining of functions is an
2250 optimization and it really ``works'' only in optimizing compilation.  If
2251 you don't use @samp{-O}, no function is really inline.
2252
2253 To declare a function inline, use the @code{inline} keyword in its
2254 declaration, like this:
2255
2256 @example
2257 inline int
2258 inc (int *a)
2259 @{
2260   (*a)++;
2261 @}
2262 @end example
2263
2264 (If you are writing a header file to be included in ANSI C programs, write
2265 @code{__inline__} instead of @code{inline}.  @xref{Alternate Keywords}.)
2266 You can also make all ``simple enough'' functions inline with the option
2267 @samp{-finline-functions}. 
2268
2269 Note that certain usages in a function definition can make it unsuitable
2270 for inline substitution.  Among these usages are: use of varargs, use of
2271 alloca, use of variable sized data types (@pxref{Variable Length}),
2272 use of computed goto (@pxref{Labels as Values}), use of nonlocal goto,
2273 and nested functions (@pxref{Nested Functions}).  Using @samp{-Winline}
2274 will warn when a function marked @code{inline} could not be substituted,
2275 and will give the reason for the failure.
2276
2277 Note that in C and Objective C, unlike C++, the @code{inline} keyword
2278 does not affect the linkage of the function.
2279
2280 @cindex automatic @code{inline} for C++ member fns
2281 @cindex @code{inline} automatic for C++ member fns
2282 @cindex member fns, automatically @code{inline}
2283 @cindex C++ member fns, automatically @code{inline}
2284 GNU CC automatically inlines member functions defined within the class
2285 body of C++ programs even if they are not explicitly declared
2286 @code{inline}.  (You can override this with @samp{-fno-default-inline};
2287 @pxref{C++ Dialect Options,,Options Controlling C++ Dialect}.)
2288
2289 @cindex inline functions, omission of
2290 When a function is both inline and @code{static}, if all calls to the
2291 function are integrated into the caller, and the function's address is
2292 never used, then the function's own assembler code is never referenced.
2293 In this case, GNU CC does not actually output assembler code for the
2294 function, unless you specify the option @samp{-fkeep-inline-functions}.
2295 Some calls cannot be integrated for various reasons (in particular,
2296 calls that precede the function's definition cannot be integrated, and
2297 neither can recursive calls within the definition).  If there is a
2298 nonintegrated call, then the function is compiled to assembler code as
2299 usual.  The function must also be compiled as usual if the program
2300 refers to its address, because that can't be inlined.
2301
2302 @cindex non-static inline function
2303 When an inline function is not @code{static}, then the compiler must assume
2304 that there may be calls from other source files; since a global symbol can
2305 be defined only once in any program, the function must not be defined in
2306 the other source files, so the calls therein cannot be integrated.
2307 Therefore, a non-@code{static} inline function is always compiled on its
2308 own in the usual fashion.
2309
2310 If you specify both @code{inline} and @code{extern} in the function
2311 definition, then the definition is used only for inlining.  In no case
2312 is the function compiled on its own, not even if you refer to its
2313 address explicitly.  Such an address becomes an external reference, as
2314 if you had only declared the function, and had not defined it.
2315
2316 This combination of @code{inline} and @code{extern} has almost the
2317 effect of a macro.  The way to use it is to put a function definition in
2318 a header file with these keywords, and put another copy of the
2319 definition (lacking @code{inline} and @code{extern}) in a library file.
2320 The definition in the header file will cause most calls to the function
2321 to be inlined.  If any uses of the function remain, they will refer to
2322 the single copy in the library.
2323
2324 GNU C does not inline any functions when not optimizing.  It is not
2325 clear whether it is better to inline or not, in this case, but we found
2326 that a correct implementation when not optimizing was difficult.  So we
2327 did the easy thing, and turned it off.
2328
2329 @node Extended Asm
2330 @section Assembler Instructions with C Expression Operands
2331 @cindex extended @code{asm}
2332 @cindex @code{asm} expressions
2333 @cindex assembler instructions
2334 @cindex registers
2335
2336 In an assembler instruction using @code{asm}, you can specify the
2337 operands of the instruction using C expressions.  This means you need not
2338 guess which registers or memory locations will contain the data you want
2339 to use.
2340
2341 You must specify an assembler instruction template much like what
2342 appears in a machine description, plus an operand constraint string for
2343 each operand.
2344
2345 For example, here is how to use the 68881's @code{fsinx} instruction:
2346
2347 @example
2348 asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
2349 @end example
2350
2351 @noindent
2352 Here @code{angle} is the C expression for the input operand while
2353 @code{result} is that of the output operand.  Each has @samp{"f"} as its
2354 operand constraint, saying that a floating point register is required.
2355 The @samp{=} in @samp{=f} indicates that the operand is an output; all
2356 output operands' constraints must use @samp{=}.  The constraints use the
2357 same language used in the machine description (@pxref{Constraints}).
2358
2359 Each operand is described by an operand-constraint string followed by
2360 the C expression in parentheses.  A colon separates the assembler
2361 template from the first output operand and another separates the last
2362 output operand from the first input, if any.  Commas separate the
2363 operands within each group.  The total number of operands is limited to
2364 ten or to the maximum number of operands in any instruction pattern in
2365 the machine description, whichever is greater.
2366
2367 If there are no output operands but there are input operands, you must
2368 place two consecutive colons surrounding the place where the output
2369 operands would go.
2370
2371 Output operand expressions must be lvalues; the compiler can check this.
2372 The input operands need not be lvalues.  The compiler cannot check
2373 whether the operands have data types that are reasonable for the
2374 instruction being executed.  It does not parse the assembler instruction
2375 template and does not know what it means or even whether it is valid
2376 assembler input.  The extended @code{asm} feature is most often used for
2377 machine instructions the compiler itself does not know exist.  If
2378 the output expression cannot be directly addressed (for example, it is a
2379 bit field), your constraint must allow a register.  In that case, GNU CC
2380 will use the register as the output of the @code{asm}, and then store
2381 that register into the output.
2382
2383 The ordinary output operands must be write-only; GNU CC will assume that
2384 the values in these operands before the instruction are dead and need
2385 not be generated.  Extended asm supports input-output or read-write
2386 operands.  Use the constraint character @samp{+} to indicate such an
2387 operand and list it with the output operands.
2388
2389 When the constraints for the read-write operand (or the operand in which
2390 only some of the bits are to be changed) allows a register, you may, as
2391 an alternative, logically split its function into two separate operands,
2392 one input operand and one write-only output operand.  The connection
2393 between them is expressed by constraints which say they need to be in
2394 the same location when the instruction executes.  You can use the same C
2395 expression for both operands, or different expressions.  For example,
2396 here we write the (fictitious) @samp{combine} instruction with
2397 @code{bar} as its read-only source operand and @code{foo} as its
2398 read-write destination:
2399
2400 @example
2401 asm ("combine %2,%0" : "=r" (foo) : "0" (foo), "g" (bar));
2402 @end example
2403
2404 @noindent
2405 The constraint @samp{"0"} for operand 1 says that it must occupy the
2406 same location as operand 0.  A digit in constraint is allowed only in an
2407 input operand and it must refer to an output operand.
2408
2409 Only a digit in the constraint can guarantee that one operand will be in
2410 the same place as another.  The mere fact that @code{foo} is the value
2411 of both operands is not enough to guarantee that they will be in the
2412 same place in the generated assembler code.  The following would not
2413 work reliably:
2414
2415 @example
2416 asm ("combine %2,%0" : "=r" (foo) : "r" (foo), "g" (bar));
2417 @end example
2418
2419 Various optimizations or reloading could cause operands 0 and 1 to be in
2420 different registers; GNU CC knows no reason not to do so.  For example, the
2421 compiler might find a copy of the value of @code{foo} in one register and
2422 use it for operand 1, but generate the output operand 0 in a different
2423 register (copying it afterward to @code{foo}'s own address).  Of course,
2424 since the register for operand 1 is not even mentioned in the assembler
2425 code, the result will not work, but GNU CC can't tell that.
2426
2427 Some instructions clobber specific hard registers.  To describe this,
2428 write a third colon after the input operands, followed by the names of
2429 the clobbered hard registers (given as strings).  Here is a realistic
2430 example for the VAX:
2431
2432 @example
2433 asm volatile ("movc3 %0,%1,%2"
2434               : /* no outputs */
2435               : "g" (from), "g" (to), "g" (count)
2436               : "r0", "r1", "r2", "r3", "r4", "r5");
2437 @end example
2438
2439 It is an error for a clobber description to overlap an input or output
2440 operand (for example, an operand describing a register class with one
2441 member, mentioned in the clobber list).  Most notably, it is invalid to
2442 describe that an input operand is modified, but unused as output.  It has
2443 to be specified as an input and output operand anyway.  Note that if there
2444 are only unused output operands, you will then also need to specify
2445 @code{volatile} for the @code{asm} construct, as described below.
2446
2447 If you refer to a particular hardware register from the assembler code,
2448 you will probably have to list the register after the third colon to
2449 tell the compiler the register's value is modified.  In some assemblers,
2450 the register names begin with @samp{%}; to produce one @samp{%} in the
2451 assembler code, you must write @samp{%%} in the input.
2452
2453 If your assembler instruction can alter the condition code register, add
2454 @samp{cc} to the list of clobbered registers.  GNU CC on some machines
2455 represents the condition codes as a specific hardware register;
2456 @samp{cc} serves to name this register.  On other machines, the
2457 condition code is handled differently, and specifying @samp{cc} has no
2458 effect.  But it is valid no matter what the machine.
2459
2460 If your assembler instruction modifies memory in an unpredictable
2461 fashion, add @samp{memory} to the list of clobbered registers.  This
2462 will cause GNU CC to not keep memory values cached in registers across
2463 the assembler instruction.
2464
2465 You can put multiple assembler instructions together in a single
2466 @code{asm} template, separated either with newlines (written as
2467 @samp{\n}) or with semicolons if the assembler allows such semicolons.
2468 The GNU assembler allows semicolons and most Unix assemblers seem to do
2469 so.  The input operands are guaranteed not to use any of the clobbered
2470 registers, and neither will the output operands' addresses, so you can
2471 read and write the clobbered registers as many times as you like.  Here
2472 is an example of multiple instructions in a template; it assumes the
2473 subroutine @code{_foo} accepts arguments in registers 9 and 10:
2474
2475 @example
2476 asm ("movl %0,r9;movl %1,r10;call _foo"
2477      : /* no outputs */
2478      : "g" (from), "g" (to)
2479      : "r9", "r10");
2480 @end example
2481
2482 Unless an output operand has the @samp{&} constraint modifier, GNU CC
2483 may allocate it in the same register as an unrelated input operand, on
2484 the assumption the inputs are consumed before the outputs are produced.
2485 This assumption may be false if the assembler code actually consists of
2486 more than one instruction.  In such a case, use @samp{&} for each output
2487 operand that may not overlap an input.  @xref{Modifiers}.
2488
2489 If you want to test the condition code produced by an assembler
2490 instruction, you must include a branch and a label in the @code{asm}
2491 construct, as follows:
2492
2493 @example
2494 asm ("clr %0;frob %1;beq 0f;mov #1,%0;0:"
2495      : "g" (result)
2496      : "g" (input));
2497 @end example
2498
2499 @noindent
2500 This assumes your assembler supports local labels, as the GNU assembler
2501 and most Unix assemblers do.
2502
2503 Speaking of labels, jumps from one @code{asm} to another are not
2504 supported.  The compiler's optimizers do not know about these jumps, and
2505 therefore they cannot take account of them when deciding how to
2506 optimize.
2507
2508 @cindex macros containing @code{asm}
2509 Usually the most convenient way to use these @code{asm} instructions is to
2510 encapsulate them in macros that look like functions.  For example,
2511
2512 @example
2513 #define sin(x)       \
2514 (@{ double __value, __arg = (x);   \
2515    asm ("fsinx %1,%0": "=f" (__value): "f" (__arg));  \
2516    __value; @})
2517 @end example
2518
2519 @noindent
2520 Here the variable @code{__arg} is used to make sure that the instruction
2521 operates on a proper @code{double} value, and to accept only those
2522 arguments @code{x} which can convert automatically to a @code{double}.
2523
2524 Another way to make sure the instruction operates on the correct data
2525 type is to use a cast in the @code{asm}.  This is different from using a
2526 variable @code{__arg} in that it converts more different types.  For
2527 example, if the desired type were @code{int}, casting the argument to
2528 @code{int} would accept a pointer with no complaint, while assigning the
2529 argument to an @code{int} variable named @code{__arg} would warn about
2530 using a pointer unless the caller explicitly casts it.
2531
2532 If an @code{asm} has output operands, GNU CC assumes for optimization
2533 purposes the instruction has no side effects except to change the output
2534 operands.  This does not mean instructions with a side effect cannot be
2535 used, but you must be careful, because the compiler may eliminate them
2536 if the output operands aren't used, or move them out of loops, or
2537 replace two with one if they constitute a common subexpression.  Also,
2538 if your instruction does have a side effect on a variable that otherwise
2539 appears not to change, the old value of the variable may be reused later
2540 if it happens to be found in a register.
2541
2542 You can prevent an @code{asm} instruction from being deleted, moved
2543 significantly, or combined, by writing the keyword @code{volatile} after
2544 the @code{asm}.  For example:
2545
2546 @example
2547 #define get_and_set_priority(new)  \
2548 (@{ int __old; \
2549    asm volatile ("get_and_set_priority %0, %1": "=g" (__old) : "g" (new)); \
2550    __old; @})
2551 @end example
2552
2553 @noindent
2554 If you write an @code{asm} instruction with no outputs, GNU CC will know
2555 the instruction has side-effects and will not delete the instruction or
2556 move it outside of loops.  If the side-effects of your instruction are
2557 not purely external, but will affect variables in your program in ways
2558 other than reading the inputs and clobbering the specified registers or
2559 memory, you should write the @code{volatile} keyword to prevent future
2560 versions of GNU CC from moving the instruction around within a core
2561 region.
2562
2563 An @code{asm} instruction without any operands or clobbers (and ``old
2564 style'' @code{asm}) will not be deleted or moved significantly,
2565 regardless, unless it is unreachable, the same wasy as if you had
2566 written a @code{volatile} keyword.
2567
2568 Note that even a volatile @code{asm} instruction can be moved in ways
2569 that appear insignificant to the compiler, such as across jump
2570 instructions.  You can't expect a sequence of volatile @code{asm}
2571 instructions to remain perfectly consecutive.  If you want consecutive
2572 output, use a single @code{asm}.
2573
2574 It is a natural idea to look for a way to give access to the condition
2575 code left by the assembler instruction.  However, when we attempted to
2576 implement this, we found no way to make it work reliably.  The problem
2577 is that output operands might need reloading, which would result in
2578 additional following ``store'' instructions.  On most machines, these
2579 instructions would alter the condition code before there was time to
2580 test it.  This problem doesn't arise for ordinary ``test'' and
2581 ``compare'' instructions because they don't have any output operands.
2582
2583 If you are writing a header file that should be includable in ANSI C
2584 programs, write @code{__asm__} instead of @code{asm}.  @xref{Alternate
2585 Keywords}.
2586
2587 @subsection i386 floating point asm operands
2588
2589 There are several rules on the usage of stack-like regs in
2590 asm_operands insns.  These rules apply only to the operands that are
2591 stack-like regs:
2592
2593 @enumerate
2594 @item
2595 Given a set of input regs that die in an asm_operands, it is
2596 necessary to know which are implicitly popped by the asm, and
2597 which must be explicitly popped by gcc.
2598
2599 An input reg that is implicitly popped by the asm must be
2600 explicitly clobbered, unless it is constrained to match an
2601 output operand.
2602
2603 @item
2604 For any input reg that is implicitly popped by an asm, it is
2605 necessary to know how to adjust the stack to compensate for the pop.
2606 If any non-popped input is closer to the top of the reg-stack than
2607 the implicitly popped reg, it would not be possible to know what the
2608 stack looked like --- it's not clear how the rest of the stack ``slides
2609 up''.
2610
2611 All implicitly popped input regs must be closer to the top of
2612 the reg-stack than any input that is not implicitly popped.
2613
2614 It is possible that if an input dies in an insn, reload might
2615 use the input reg for an output reload.  Consider this example:
2616
2617 @example
2618 asm ("foo" : "=t" (a) : "f" (b));
2619 @end example
2620
2621 This asm says that input B is not popped by the asm, and that
2622 the asm pushes a result onto the reg-stack, ie, the stack is one
2623 deeper after the asm than it was before.  But, it is possible that
2624 reload will think that it can use the same reg for both the input and
2625 the output, if input B dies in this insn.
2626
2627 If any input operand uses the @code{f} constraint, all output reg
2628 constraints must use the @code{&} earlyclobber.
2629
2630 The asm above would be written as
2631
2632 @example
2633 asm ("foo" : "=&t" (a) : "f" (b));
2634 @end example
2635
2636 @item
2637 Some operands need to be in particular places on the stack.  All
2638 output operands fall in this category --- there is no other way to
2639 know which regs the outputs appear in unless the user indicates
2640 this in the constraints.
2641
2642 Output operands must specifically indicate which reg an output
2643 appears in after an asm.  @code{=f} is not allowed: the operand
2644 constraints must select a class with a single reg.
2645
2646 @item
2647 Output operands may not be ``inserted'' between existing stack regs.
2648 Since no 387 opcode uses a read/write operand, all output operands
2649 are dead before the asm_operands, and are pushed by the asm_operands.
2650 It makes no sense to push anywhere but the top of the reg-stack.
2651
2652 Output operands must start at the top of the reg-stack: output
2653 operands may not ``skip'' a reg.
2654
2655 @item
2656 Some asm statements may need extra stack space for internal
2657 calculations.  This can be guaranteed by clobbering stack registers
2658 unrelated to the inputs and outputs.
2659
2660 @end enumerate
2661
2662 Here are a couple of reasonable asms to want to write.  This asm
2663 takes one input, which is internally popped, and produces two outputs.
2664
2665 @example
2666 asm ("fsincos" : "=t" (cos), "=u" (sin) : "0" (inp));
2667 @end example
2668
2669 This asm takes two inputs, which are popped by the @code{fyl2xp1} opcode,
2670 and replaces them with one output.  The user must code the @code{st(1)}
2671 clobber for reg-stack.c to know that @code{fyl2xp1} pops both inputs.
2672
2673 @example
2674 asm ("fyl2xp1" : "=t" (result) : "0" (x), "u" (y) : "st(1)");
2675 @end example
2676
2677 @ifclear INTERNALS
2678 @c Show the details on constraints if they do not appear elsewhere in
2679 @c the manual
2680 @include md.texi
2681 @end ifclear
2682
2683 @node Asm Labels
2684 @section Controlling Names Used in Assembler Code
2685 @cindex assembler names for identifiers
2686 @cindex names used in assembler code
2687 @cindex identifiers, names in assembler code
2688
2689 You can specify the name to be used in the assembler code for a C
2690 function or variable by writing the @code{asm} (or @code{__asm__})
2691 keyword after the declarator as follows:
2692
2693 @example
2694 int foo asm ("myfoo") = 2;
2695 @end example
2696
2697 @noindent
2698 This specifies that the name to be used for the variable @code{foo} in
2699 the assembler code should be @samp{myfoo} rather than the usual
2700 @samp{_foo}.
2701
2702 On systems where an underscore is normally prepended to the name of a C
2703 function or variable, this feature allows you to define names for the
2704 linker that do not start with an underscore.
2705
2706 You cannot use @code{asm} in this way in a function @emph{definition}; but
2707 you can get the same effect by writing a declaration for the function
2708 before its definition and putting @code{asm} there, like this:
2709
2710 @example
2711 extern func () asm ("FUNC");
2712
2713 func (x, y)
2714      int x, y;
2715 @dots{}
2716 @end example
2717
2718 It is up to you to make sure that the assembler names you choose do not
2719 conflict with any other assembler symbols.  Also, you must not use a
2720 register name; that would produce completely invalid assembler code.  GNU
2721 CC does not as yet have the ability to store static variables in registers.
2722 Perhaps that will be added.
2723
2724 @node Explicit Reg Vars
2725 @section Variables in Specified Registers
2726 @cindex explicit register variables
2727 @cindex variables in specified registers
2728 @cindex specified registers
2729 @cindex registers, global allocation
2730
2731 GNU C allows you to put a few global variables into specified hardware
2732 registers.  You can also specify the register in which an ordinary
2733 register variable should be allocated.
2734
2735 @itemize @bullet
2736 @item
2737 Global register variables reserve registers throughout the program.
2738 This may be useful in programs such as programming language
2739 interpreters which have a couple of global variables that are accessed
2740 very often.
2741
2742 @item
2743 Local register variables in specific registers do not reserve the
2744 registers.  The compiler's data flow analysis is capable of determining
2745 where the specified registers contain live values, and where they are
2746 available for other uses.  Stores into local register variables may be deleted
2747 when they appear to be dead according to dataflow analysis.  References
2748 to local register variables may be deleted or moved or simplified.
2749
2750 These local variables are sometimes convenient for use with the extended
2751 @code{asm} feature (@pxref{Extended Asm}), if you want to write one
2752 output of the assembler instruction directly into a particular register.
2753 (This will work provided the register you specify fits the constraints
2754 specified for that operand in the @code{asm}.)
2755 @end itemize
2756
2757 @menu
2758 * Global Reg Vars::
2759 * Local Reg Vars::
2760 @end menu
2761
2762 @node Global Reg Vars
2763 @subsection Defining Global Register Variables
2764 @cindex global register variables
2765 @cindex registers, global variables in
2766
2767 You can define a global register variable in GNU C like this:
2768
2769 @example
2770 register int *foo asm ("a5");
2771 @end example
2772
2773 @noindent
2774 Here @code{a5} is the name of the register which should be used.  Choose a
2775 register which is normally saved and restored by function calls on your
2776 machine, so that library routines will not clobber it.
2777
2778 Naturally the register name is cpu-dependent, so you would need to
2779 conditionalize your program according to cpu type.  The register
2780 @code{a5} would be a good choice on a 68000 for a variable of pointer
2781 type.  On machines with register windows, be sure to choose a ``global''
2782 register that is not affected magically by the function call mechanism.
2783
2784 In addition, operating systems on one type of cpu may differ in how they
2785 name the registers; then you would need additional conditionals.  For
2786 example, some 68000 operating systems call this register @code{%a5}.
2787
2788 Eventually there may be a way of asking the compiler to choose a register
2789 automatically, but first we need to figure out how it should choose and
2790 how to enable you to guide the choice.  No solution is evident.
2791
2792 Defining a global register variable in a certain register reserves that
2793 register entirely for this use, at least within the current compilation.
2794 The register will not be allocated for any other purpose in the functions
2795 in the current compilation.  The register will not be saved and restored by
2796 these functions.  Stores into this register are never deleted even if they
2797 would appear to be dead, but references may be deleted or moved or
2798 simplified.
2799
2800 It is not safe to access the global register variables from signal
2801 handlers, or from more than one thread of control, because the system
2802 library routines may temporarily use the register for other things (unless
2803 you recompile them specially for the task at hand).
2804
2805 @cindex @code{qsort}, and global register variables
2806 It is not safe for one function that uses a global register variable to
2807 call another such function @code{foo} by way of a third function
2808 @code{lose} that was compiled without knowledge of this variable (i.e. in a
2809 different source file in which the variable wasn't declared).  This is
2810 because @code{lose} might save the register and put some other value there.
2811 For example, you can't expect a global register variable to be available in
2812 the comparison-function that you pass to @code{qsort}, since @code{qsort}
2813 might have put something else in that register.  (If you are prepared to
2814 recompile @code{qsort} with the same global register variable, you can
2815 solve this problem.)
2816
2817 If you want to recompile @code{qsort} or other source files which do not
2818 actually use your global register variable, so that they will not use that
2819 register for any other purpose, then it suffices to specify the compiler
2820 option @samp{-ffixed-@var{reg}}.  You need not actually add a global
2821 register declaration to their source code.
2822
2823 A function which can alter the value of a global register variable cannot
2824 safely be called from a function compiled without this variable, because it
2825 could clobber the value the caller expects to find there on return.
2826 Therefore, the function which is the entry point into the part of the
2827 program that uses the global register variable must explicitly save and
2828 restore the value which belongs to its caller.
2829
2830 @cindex register variable after @code{longjmp}
2831 @cindex global register after @code{longjmp}
2832 @cindex value after @code{longjmp}
2833 @findex longjmp
2834 @findex setjmp
2835 On most machines, @code{longjmp} will restore to each global register
2836 variable the value it had at the time of the @code{setjmp}.  On some
2837 machines, however, @code{longjmp} will not change the value of global
2838 register variables.  To be portable, the function that called @code{setjmp}
2839 should make other arrangements to save the values of the global register
2840 variables, and to restore them in a @code{longjmp}.  This way, the same
2841 thing will happen regardless of what @code{longjmp} does.
2842
2843 All global register variable declarations must precede all function
2844 definitions.  If such a declaration could appear after function
2845 definitions, the declaration would be too late to prevent the register from
2846 being used for other purposes in the preceding functions.
2847
2848 Global register variables may not have initial values, because an
2849 executable file has no means to supply initial contents for a register.
2850
2851 On the Sparc, there are reports that g3 @dots{} g7 are suitable
2852 registers, but certain library functions, such as @code{getwd}, as well
2853 as the subroutines for division and remainder, modify g3 and g4.  g1 and
2854 g2 are local temporaries.
2855
2856 On the 68000, a2 @dots{} a5 should be suitable, as should d2 @dots{} d7.
2857 Of course, it will not do to use more than a few of those.
2858
2859 @node Local Reg Vars
2860 @subsection Specifying Registers for Local Variables
2861 @cindex local variables, specifying registers
2862 @cindex specifying registers for local variables
2863 @cindex registers for local variables
2864
2865 You can define a local register variable with a specified register
2866 like this:
2867
2868 @example
2869 register int *foo asm ("a5");
2870 @end example
2871
2872 @noindent
2873 Here @code{a5} is the name of the register which should be used.  Note
2874 that this is the same syntax used for defining global register
2875 variables, but for a local variable it would appear within a function.
2876
2877 Naturally the register name is cpu-dependent, but this is not a
2878 problem, since specific registers are most often useful with explicit
2879 assembler instructions (@pxref{Extended Asm}).  Both of these things
2880 generally require that you conditionalize your program according to
2881 cpu type.
2882
2883 In addition, operating systems on one type of cpu may differ in how they
2884 name the registers; then you would need additional conditionals.  For
2885 example, some 68000 operating systems call this register @code{%a5}.
2886
2887 Defining such a register variable does not reserve the register; it
2888 remains available for other uses in places where flow control determines
2889 the variable's value is not live.  However, these registers are made
2890 unavailable for use in the reload pass; excessive use of this feature
2891 leaves the compiler too few available registers to compile certain
2892 functions.
2893
2894 This option does not guarantee that GNU CC will generate code that has
2895 this variable in the register you specify at all times.  You may not
2896 code an explicit reference to this register in an @code{asm} statement
2897 and assume it will always refer to this variable.
2898
2899 Stores into local register variables may be deleted when they appear to be dead
2900 according to dataflow analysis.  References to local register variables may
2901 be deleted or moved or simplified.
2902
2903 @node Alternate Keywords
2904 @section Alternate Keywords
2905 @cindex alternate keywords
2906 @cindex keywords, alternate
2907
2908 The option @samp{-traditional} disables certain keywords; @samp{-ansi}
2909 disables certain others.  This causes trouble when you want to use GNU C
2910 extensions, or ANSI C features, in a general-purpose header file that
2911 should be usable by all programs, including ANSI C programs and traditional
2912 ones.  The keywords @code{asm}, @code{typeof} and @code{inline} cannot be
2913 used since they won't work in a program compiled with @samp{-ansi}, while
2914 the keywords @code{const}, @code{volatile}, @code{signed}, @code{typeof}
2915 and @code{inline} won't work in a program compiled with
2916 @samp{-traditional}.@refill
2917
2918 The way to solve these problems is to put @samp{__} at the beginning and
2919 end of each problematical keyword.  For example, use @code{__asm__}
2920 instead of @code{asm}, @code{__const__} instead of @code{const}, and
2921 @code{__inline__} instead of @code{inline}.
2922
2923 Other C compilers won't accept these alternative keywords; if you want to
2924 compile with another compiler, you can define the alternate keywords as
2925 macros to replace them with the customary keywords.  It looks like this:
2926
2927 @example
2928 #ifndef __GNUC__
2929 #define __asm__ asm
2930 #endif
2931 @end example
2932
2933 @findex __extension__
2934 @samp{-pedantic} causes warnings for many GNU C extensions.  You can
2935 prevent such warnings within one expression by writing
2936 @code{__extension__} before the expression.  @code{__extension__} has no
2937 effect aside from this.
2938
2939 @node Incomplete Enums
2940 @section Incomplete @code{enum} Types
2941
2942 You can define an @code{enum} tag without specifying its possible values.
2943 This results in an incomplete type, much like what you get if you write
2944 @code{struct foo} without describing the elements.  A later declaration
2945 which does specify the possible values completes the type.
2946
2947 You can't allocate variables or storage using the type while it is
2948 incomplete.  However, you can work with pointers to that type.
2949
2950 This extension may not be very useful, but it makes the handling of
2951 @code{enum} more consistent with the way @code{struct} and @code{union}
2952 are handled.
2953
2954 This extension is not supported by GNU C++.
2955
2956 @node Function Names
2957 @section Function Names as Strings
2958
2959 GNU CC predefines two string variables to be the name of the current function.
2960 The variable @code{__FUNCTION__} is the name of the function as it appears
2961 in the source.  The variable @code{__PRETTY_FUNCTION__} is the name of
2962 the function pretty printed in a language specific fashion.
2963
2964 These names are always the same in a C function, but in a C++ function
2965 they may be different.  For example, this program:
2966
2967 @smallexample
2968 extern "C" @{
2969 extern int printf (char *, ...);
2970 @}
2971
2972 class a @{
2973  public:
2974   sub (int i)
2975     @{
2976       printf ("__FUNCTION__ = %s\n", __FUNCTION__);
2977       printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
2978     @}
2979 @};
2980
2981 int
2982 main (void)
2983 @{
2984   a ax;
2985   ax.sub (0);
2986   return 0;
2987 @}
2988 @end smallexample
2989
2990 @noindent
2991 gives this output:
2992
2993 @smallexample
2994 __FUNCTION__ = sub
2995 __PRETTY_FUNCTION__ = int  a::sub (int)
2996 @end smallexample
2997
2998 These names are not macros: they are predefined string variables.
2999 For example, @samp{#ifdef __FUNCTION__} does not have any special
3000 meaning inside a function, since the preprocessor does not do anything
3001 special with the identifier @code{__FUNCTION__}.
3002
3003 @node Return Address
3004 @section Getting the Return or Frame Address of a Function
3005
3006 These functions may be used to get information about the callers of a
3007 function.
3008
3009 @table @code
3010 @findex __builtin_return_address
3011 @item __builtin_return_address (@var{level})
3012 This function returns the return address of the current function, or of
3013 one of its callers.  The @var{level} argument is number of frames to
3014 scan up the call stack.  A value of @code{0} yields the return address
3015 of the current function, a value of @code{1} yields the return address
3016 of the caller of the current function, and so forth.
3017
3018 The @var{level} argument must be a constant integer.
3019
3020 On some machines it may be impossible to determine the return address of
3021 any function other than the current one; in such cases, or when the top
3022 of the stack has been reached, this function will return @code{0}.
3023
3024 This function should only be used with a non-zero argument for debugging
3025 purposes.
3026
3027 @findex __builtin_frame_address
3028 @item __builtin_frame_address (@var{level})
3029 This function is similar to @code{__builtin_return_address}, but it
3030 returns the address of the function frame rather than the return address
3031 of the function.  Calling @code{__builtin_frame_address} with a value of
3032 @code{0} yields the frame address of the current function, a value of
3033 @code{1} yields the frame address of the caller of the current function,
3034 and so forth.
3035
3036 The frame is the area on the stack which holds local variables and saved
3037 registers.  The frame address is normally the address of the first word
3038 pushed on to the stack by the function.  However, the exact definition
3039 depends upon the processor and the calling convention.  If the processor
3040 has a dedicated frame pointer register, and the function has a frame,
3041 then @code{__builtin_frame_address} will return the value of the frame
3042 pointer register.
3043
3044 The caveats that apply to @code{__builtin_return_address} apply to this
3045 function as well.
3046 @end table
3047
3048 @node Other Builtins
3049 @section Other built-in functions provided by GNU CC
3050
3051 GNU CC provides a large number of built-in functions other than the ones
3052 mentioned above.  Some of these are for internal use in the processing
3053 of exceptions or variable-length argument lists and will not be
3054 documented here because they may change from time to time; we do not
3055 recommend general use of these functions.
3056
3057 The remaining functions are provided for optimization purposes.
3058
3059 GNU CC includes builtin versions of many of the functions in the
3060 standard C library.  These will always be treated as having the same
3061 meaning as the C library function even if you specify the
3062 @samp{-fno-builtin} (@pxref{C Dialect Options}) option.  These functions
3063 correspond to the C library functions @code{alloca}, @code{ffs},
3064 @code{abs}, @code{fabsf}, @code{fabs}, @code{fabsl}, @code{labs},
3065 @code{memcpy}, @code{memcmp}, @code{strcmp}, @code{strcpy},
3066 @code{strlen}, @code{sqrtf}, @code{sqrt}, @code{sqrtl}, @code{sinf},
3067 @code{sin}, @code{sinl}, @code{cosf}, @code{cos}, and @code{cosl}.
3068
3069 @findex __builtin_constant_p
3070 You can use the builtin function @code{__builtin_constant_p} to
3071 determine if a value is known to be constant at compile-time and hence
3072 that GNU CC can perform constant-folding on expressions involving that
3073 value.  The argument of the function is the value to test.  The function
3074 returns the integer 1 if the argument is known to be a compile-time
3075 constant and 0 if it is not known to be a compile-time constant.  A
3076 return of 0 does not indicate that the value is @emph{not} a constant,
3077 but merely that GNU CC cannot prove it is a constant with the specified
3078 value of the @samp{-O} option.
3079
3080 You would typically use this function in an embedded application where
3081 memory was a critical resource.  If you have some complex calculation,
3082 you may want it to be folded if it involves constants, but need to call
3083 a function if it does not.  For example:
3084
3085 @smallexample
3086 #define Scale_Value(X)  \
3087   (__builtin_constant_p (X) ? ((X) * SCALE + OFFSET) : Scale (X))
3088 @end smallexample
3089
3090 You may use this builtin function in either a macro or an inline
3091 function.  However, if you use it in an inlined function and pass an
3092 argument of the function as the argument to the builtin, GNU CC will
3093 never return 1 when you call the inline function with a string constant
3094 or constructor expression (@pxref{Constructors}) and will not return 1
3095 when you pass a constant numeric value to the inline function unless you
3096 specify the @samp{-O} option.
3097
3098 @node Deprecated Features
3099 @section Deprecated Features
3100
3101 In the past, the GNU C++ compiler was extended to experiment with new
3102 features, at a time when the C++ language was still evolving. Now that
3103 the C++ standard is complete, some of those features are superceded by
3104 superior alternatives. Using the old features might cause a warning in
3105 some cases that the feature will be dropped in the future. In other
3106 cases, the feature might be gone already.
3107
3108 While the list below is not exhaustive, it documents some of the options
3109 that are now deprecated:
3110
3111 @table @code
3112 @item -fthis-is-variable
3113 In early versions of C++, assignment to this could be used to implement
3114 application-defined memory allocation. Now, allocation functions
3115 (@samp{operator new}) are the standard-conforming way to achieve the
3116 same effect.
3117
3118 @item -fexternal-templates
3119 @itemx -falt-external-templates
3120 These are two of the many ways for g++ to implement template
3121 instantiation. @xref{Template Instantiation}. The C++ standard clearly
3122 defines how template definitions have to be organized across
3123 implementation units. g++ has an implicit instantiation mechanism that
3124 should work just fine for standard-conforming code.
3125
3126 @end table
3127
3128 @node C++ Extensions
3129 @chapter Extensions to the C++ Language
3130 @cindex extensions, C++ language
3131 @cindex C++ language extensions
3132
3133 The GNU compiler provides these extensions to the C++ language (and you
3134 can also use most of the C language extensions in your C++ programs).  If you
3135 want to write code that checks whether these features are available, you can
3136 test for the GNU compiler the same way as for C programs: check for a
3137 predefined macro @code{__GNUC__}.  You can also use @code{__GNUG__} to
3138 test specifically for GNU C++ (@pxref{Standard Predefined,,Standard
3139 Predefined Macros,cpp.info,The C Preprocessor}).
3140
3141 @menu
3142 * Naming Results::      Giving a name to C++ function return values.
3143 * Min and Max::         C++ Minimum and maximum operators.
3144 * Destructors and Goto:: Goto is safe to use in C++ even when destructors
3145                            are needed.
3146 * C++ Interface::       You can use a single C++ header file for both
3147                          declarations and definitions.
3148 * Template Instantiation:: Methods for ensuring that exactly one copy of
3149                          each needed template instantiation is emitted.
3150 * Bound member functions:: You can extract a function pointer to the
3151                         method denoted by a @samp{->*} or @samp{.*} expression.
3152 * C++ Signatures::      You can specify abstract types to get subtype
3153                          polymorphism independent from inheritance.
3154                         
3155 @end menu
3156
3157 @node Naming Results
3158 @section Named Return Values in C++
3159
3160 @cindex @code{return}, in C++ function header
3161 @cindex return value, named, in C++
3162 @cindex named return value in C++
3163 @cindex C++ named return value
3164 GNU C++ extends the function-definition syntax to allow you to specify a
3165 name for the result of a function outside the body of the definition, in
3166 C++ programs:
3167
3168 @example
3169 @group
3170 @var{type}
3171 @var{functionname} (@var{args}) return @var{resultname};
3172 @{
3173   @dots{}
3174   @var{body}
3175   @dots{}
3176 @}
3177 @end group
3178 @end example
3179
3180 You can use this feature to avoid an extra constructor call when
3181 a function result has a class type.  For example, consider a function
3182 @code{m}, declared as @w{@samp{X v = m ();}}, whose result is of class
3183 @code{X}:
3184
3185 @example
3186 X
3187 m ()
3188 @{
3189   X b;
3190   b.a = 23;
3191   return b;
3192 @}
3193 @end example
3194
3195 @cindex implicit argument: return value
3196 Although @code{m} appears to have no arguments, in fact it has one implicit
3197 argument: the address of the return value.  At invocation, the address
3198 of enough space to hold @code{v} is sent in as the implicit argument.
3199 Then @code{b} is constructed and its @code{a} field is set to the value
3200 23.  Finally, a copy constructor (a constructor of the form @samp{X(X&)})
3201 is applied to @code{b}, with the (implicit) return value location as the
3202 target, so that @code{v} is now bound to the return value.
3203
3204 But this is wasteful.  The local @code{b} is declared just to hold
3205 something that will be copied right out.  While a compiler that
3206 combined an ``elision'' algorithm with interprocedural data flow
3207 analysis could conceivably eliminate all of this, it is much more
3208 practical to allow you to assist the compiler in generating
3209 efficient code by manipulating the return value explicitly,
3210 thus avoiding the local variable and copy constructor altogether.
3211
3212 Using the extended GNU C++ function-definition syntax, you can avoid the
3213 temporary allocation and copying by naming @code{r} as your return value
3214 at the outset, and assigning to its @code{a} field directly:
3215
3216 @example
3217 X
3218 m () return r;
3219 @{
3220   r.a = 23;
3221 @}
3222 @end example
3223
3224 @noindent
3225 The declaration of @code{r} is a standard, proper declaration, whose effects
3226 are executed @strong{before} any of the body of @code{m}.
3227
3228 Functions of this type impose no additional restrictions; in particular,
3229 you can execute @code{return} statements, or return implicitly by
3230 reaching the end of the function body (``falling off the edge'').
3231 Cases like
3232
3233 @example
3234 X
3235 m () return r (23);
3236 @{
3237   return;
3238 @}
3239 @end example
3240
3241 @noindent
3242 (or even @w{@samp{X m () return r (23); @{ @}}}) are unambiguous, since
3243 the return value @code{r} has been initialized in either case.  The
3244 following code may be hard to read, but also works predictably:
3245
3246 @example
3247 X
3248 m () return r;
3249 @{
3250   X b;
3251   return b;
3252 @}
3253 @end example
3254
3255 The return value slot denoted by @code{r} is initialized at the outset,
3256 but the statement @samp{return b;} overrides this value.  The compiler
3257 deals with this by destroying @code{r} (calling the destructor if there
3258 is one, or doing nothing if there is not), and then reinitializing
3259 @code{r} with @code{b}.
3260
3261 This extension is provided primarily to help people who use overloaded
3262 operators, where there is a great need to control not just the
3263 arguments, but the return values of functions.  For classes where the
3264 copy constructor incurs a heavy performance penalty (especially in the
3265 common case where there is a quick default constructor), this is a major
3266 savings.  The disadvantage of this extension is that you do not control
3267 when the default constructor for the return value is called: it is
3268 always called at the beginning.
3269
3270 @node Min and Max
3271 @section Minimum and Maximum Operators in C++
3272
3273 It is very convenient to have operators which return the ``minimum'' or the
3274 ``maximum'' of two arguments.  In GNU C++ (but not in GNU C),
3275
3276 @table @code
3277 @item @var{a} <? @var{b}
3278 @findex <?
3279 @cindex minimum operator
3280 is the @dfn{minimum}, returning the smaller of the numeric values
3281 @var{a} and @var{b};
3282
3283 @item @var{a} >? @var{b}
3284 @findex >?
3285 @cindex maximum operator
3286 is the @dfn{maximum}, returning the larger of the numeric values @var{a}
3287 and @var{b}.
3288 @end table
3289
3290 These operations are not primitive in ordinary C++, since you can
3291 use a macro to return the minimum of two things in C++, as in the
3292 following example.
3293
3294 @example
3295 #define MIN(X,Y) ((X) < (Y) ? : (X) : (Y))
3296 @end example
3297
3298 @noindent
3299 You might then use @w{@samp{int min = MIN (i, j);}} to set @var{min} to
3300 the minimum value of variables @var{i} and @var{j}.
3301
3302 However, side effects in @code{X} or @code{Y} may cause unintended
3303 behavior.  For example, @code{MIN (i++, j++)} will fail, incrementing
3304 the smaller counter twice.  A GNU C extension allows you to write safe
3305 macros that avoid this kind of problem (@pxref{Naming Types,,Naming an
3306 Expression's Type}).  However, writing @code{MIN} and @code{MAX} as
3307 macros also forces you to use function-call notation for a
3308 fundamental arithmetic operation.  Using GNU C++ extensions, you can
3309 write @w{@samp{int min = i <? j;}} instead.
3310
3311 Since @code{<?} and @code{>?} are built into the compiler, they properly
3312 handle expressions with side-effects;  @w{@samp{int min = i++ <? j++;}}
3313 works correctly.
3314
3315 @node Destructors and Goto
3316 @section @code{goto} and Destructors in GNU C++
3317
3318 @cindex @code{goto} in C++
3319 @cindex destructors vs @code{goto}
3320 In C++ programs, you can safely use the @code{goto} statement.  When you
3321 use it to exit a block which contains aggregates requiring destructors,
3322 the destructors will run before the @code{goto} transfers control.
3323
3324 @cindex constructors vs @code{goto}
3325 The compiler still forbids using @code{goto} to @emph{enter} a scope
3326 that requires constructors.
3327
3328 @node C++ Interface
3329 @section Declarations and Definitions in One Header
3330
3331 @cindex interface and implementation headers, C++
3332 @cindex C++ interface and implementation headers
3333 C++ object definitions can be quite complex.  In principle, your source
3334 code will need two kinds of things for each object that you use across
3335 more than one source file.  First, you need an @dfn{interface}
3336 specification, describing its structure with type declarations and
3337 function prototypes.  Second, you need the @dfn{implementation} itself.
3338 It can be tedious to maintain a separate interface description in a
3339 header file, in parallel to the actual implementation.  It is also
3340 dangerous, since separate interface and implementation definitions may
3341 not remain parallel.
3342
3343 @cindex pragmas, interface and implementation
3344 With GNU C++, you can use a single header file for both purposes.
3345
3346 @quotation
3347 @emph{Warning:} The mechanism to specify this is in transition.  For the
3348 nonce, you must use one of two @code{#pragma} commands; in a future
3349 release of GNU C++, an alternative mechanism will make these
3350 @code{#pragma} commands unnecessary.
3351 @end quotation
3352
3353 The header file contains the full definitions, but is marked with
3354 @samp{#pragma interface} in the source code.  This allows the compiler
3355 to use the header file only as an interface specification when ordinary
3356 source files incorporate it with @code{#include}.  In the single source
3357 file where the full implementation belongs, you can use either a naming
3358 convention or @samp{#pragma implementation} to indicate this alternate
3359 use of the header file.
3360
3361 @table @code
3362 @item #pragma interface
3363 @itemx #pragma interface "@var{subdir}/@var{objects}.h"
3364 @kindex #pragma interface
3365 Use this directive in @emph{header files} that define object classes, to save
3366 space in most of the object files that use those classes.  Normally,
3367 local copies of certain information (backup copies of inline member
3368 functions, debugging information, and the internal tables that implement
3369 virtual functions) must be kept in each object file that includes class
3370 definitions.  You can use this pragma to avoid such duplication.  When a
3371 header file containing @samp{#pragma interface} is included in a
3372 compilation, this auxiliary information will not be generated (unless
3373 the main input source file itself uses @samp{#pragma implementation}).
3374 Instead, the object files will contain references to be resolved at link
3375 time.
3376
3377 The second form of this directive is useful for the case where you have
3378 multiple headers with the same name in different directories.  If you
3379 use this form, you must specify the same string to @samp{#pragma
3380 implementation}.
3381
3382 @item #pragma implementation
3383 @itemx #pragma implementation "@var{objects}.h"
3384 @kindex #pragma implementation
3385 Use this pragma in a @emph{main input file}, when you want full output from
3386 included header files to be generated (and made globally visible).  The
3387 included header file, in turn, should use @samp{#pragma interface}.
3388 Backup copies of inline member functions, debugging information, and the
3389 internal tables used to implement virtual functions are all generated in
3390 implementation files.
3391
3392 @cindex implied @code{#pragma implementation}
3393 @cindex @code{#pragma implementation}, implied
3394 @cindex naming convention, implementation headers
3395 If you use @samp{#pragma implementation} with no argument, it applies to
3396 an include file with the same basename@footnote{A file's @dfn{basename}
3397 was the name stripped of all leading path information and of trailing
3398 suffixes, such as @samp{.h} or @samp{.C} or @samp{.cc}.} as your source
3399 file.  For example, in @file{allclass.cc}, giving just
3400 @samp{#pragma implementation}
3401 by itself is equivalent to @samp{#pragma implementation "allclass.h"}.
3402
3403 In versions of GNU C++ prior to 2.6.0 @file{allclass.h} was treated as
3404 an implementation file whenever you would include it from
3405 @file{allclass.cc} even if you never specified @samp{#pragma
3406 implementation}.  This was deemed to be more trouble than it was worth,
3407 however, and disabled.
3408
3409 If you use an explicit @samp{#pragma implementation}, it must appear in
3410 your source file @emph{before} you include the affected header files.
3411
3412 Use the string argument if you want a single implementation file to
3413 include code from multiple header files.  (You must also use
3414 @samp{#include} to include the header file; @samp{#pragma
3415 implementation} only specifies how to use the file---it doesn't actually
3416 include it.)
3417
3418 There is no way to split up the contents of a single header file into
3419 multiple implementation files.
3420 @end table
3421
3422 @cindex inlining and C++ pragmas
3423 @cindex C++ pragmas, effect on inlining
3424 @cindex pragmas in C++, effect on inlining
3425 @samp{#pragma implementation} and @samp{#pragma interface} also have an
3426 effect on function inlining.
3427
3428 If you define a class in a header file marked with @samp{#pragma
3429 interface}, the effect on a function defined in that class is similar to
3430 an explicit @code{extern} declaration---the compiler emits no code at
3431 all to define an independent version of the function.  Its definition
3432 is used only for inlining with its callers.
3433
3434 Conversely, when you include the same header file in a main source file
3435 that declares it as @samp{#pragma implementation}, the compiler emits
3436 code for the function itself; this defines a version of the function
3437 that can be found via pointers (or by callers compiled without
3438 inlining).  If all calls to the function can be inlined, you can avoid
3439 emitting the function by compiling with @samp{-fno-implement-inlines}.
3440 If any calls were not inlined, you will get linker errors.
3441
3442 @node Template Instantiation
3443 @section Where's the Template?
3444
3445 @cindex template instantiation
3446
3447 C++ templates are the first language feature to require more
3448 intelligence from the environment than one usually finds on a UNIX
3449 system.  Somehow the compiler and linker have to make sure that each
3450 template instance occurs exactly once in the executable if it is needed,
3451 and not at all otherwise.  There are two basic approaches to this
3452 problem, which I will refer to as the Borland model and the Cfront model.
3453
3454 @table @asis
3455 @item Borland model
3456 Borland C++ solved the template instantiation problem by adding the code
3457 equivalent of common blocks to their linker; the compiler emits template
3458 instances in each translation unit that uses them, and the linker
3459 collapses them together.  The advantage of this model is that the linker
3460 only has to consider the object files themselves; there is no external
3461 complexity to worry about.  This disadvantage is that compilation time
3462 is increased because the template code is being compiled repeatedly.
3463 Code written for this model tends to include definitions of all
3464 templates in the header file, since they must be seen to be
3465 instantiated.
3466
3467 @item Cfront model
3468 The AT&T C++ translator, Cfront, solved the template instantiation
3469 problem by creating the notion of a template repository, an
3470 automatically maintained place where template instances are stored.  A
3471 more modern version of the repository works as follows: As individual
3472 object files are built, the compiler places any template definitions and
3473 instantiations encountered in the repository.  At link time, the link
3474 wrapper adds in the objects in the repository and compiles any needed
3475 instances that were not previously emitted.  The advantages of this
3476 model are more optimal compilation speed and the ability to use the
3477 system linker; to implement the Borland model a compiler vendor also
3478 needs to replace the linker.  The disadvantages are vastly increased
3479 complexity, and thus potential for error; for some code this can be
3480 just as transparent, but in practice it can been very difficult to build
3481 multiple programs in one directory and one program in multiple
3482 directories.  Code written for this model tends to separate definitions
3483 of non-inline member templates into a separate file, which should be
3484 compiled separately.
3485 @end table
3486
3487 When used with GNU ld version 2.8 or later on an ELF system such as
3488 Linux/GNU or Solaris 2, or on Microsoft Windows, g++ supports the
3489 Borland model.  On other systems, g++ implements neither automatic
3490 model.
3491
3492 A future version of g++ will support a hybrid model whereby the compiler
3493 will emit any instantiations for which the template definition is
3494 included in the compile, and store template definitions and
3495 instantiation context information into the object file for the rest.
3496 The link wrapper will extract that information as necessary and invoke
3497 the compiler to produce the remaining instantiations.  The linker will
3498 then combine duplicate instantiations.
3499
3500 In the mean time, you have the following options for dealing with
3501 template instantiations:
3502
3503 @enumerate
3504 @item
3505 Compile your template-using code with @samp{-frepo}.  The compiler will
3506 generate files with the extension @samp{.rpo} listing all of the
3507 template instantiations used in the corresponding object files which
3508 could be instantiated there; the link wrapper, @samp{collect2}, will
3509 then update the @samp{.rpo} files to tell the compiler where to place
3510 those instantiations and rebuild any affected object files.  The
3511 link-time overhead is negligible after the first pass, as the compiler
3512 will continue to place the instantiations in the same files.
3513
3514 This is your best option for application code written for the Borland
3515 model, as it will just work.  Code written for the Cfront model will
3516 need to be modified so that the template definitions are available at
3517 one or more points of instantiation; usually this is as simple as adding
3518 @code{#include <tmethods.cc>} to the end of each template header.
3519
3520 For library code, if you want the library to provide all of the template
3521 instantiations it needs, just try to link all of its object files
3522 together; the link will fail, but cause the instantiations to be
3523 generated as a side effect.  Be warned, however, that this may cause
3524 conflicts if multiple libraries try to provide the same instantiations.
3525 For greater control, use explicit instantiation as described in the next
3526 option.
3527
3528 @item
3529 Compile your code with @samp{-fno-implicit-templates} to disable the
3530 implicit generation of template instances, and explicitly instantiate
3531 all the ones you use.  This approach requires more knowledge of exactly
3532 which instances you need than do the others, but it's less
3533 mysterious and allows greater control.  You can scatter the explicit
3534 instantiations throughout your program, perhaps putting them in the
3535 translation units where the instances are used or the translation units
3536 that define the templates themselves; you can put all of the explicit
3537 instantiations you need into one big file; or you can create small files
3538 like
3539
3540 @example
3541 #include "Foo.h"
3542 #include "Foo.cc"
3543
3544 template class Foo<int>;
3545 template ostream& operator <<
3546                 (ostream&, const Foo<int>&);
3547 @end example
3548
3549 for each of the instances you need, and create a template instantiation
3550 library from those.
3551
3552 If you are using Cfront-model code, you can probably get away with not
3553 using @samp{-fno-implicit-templates} when compiling files that don't
3554 @samp{#include} the member template definitions.
3555
3556 If you use one big file to do the instantiations, you may want to
3557 compile it without @samp{-fno-implicit-templates} so you get all of the
3558 instances required by your explicit instantiations (but not by any
3559 other files) without having to specify them as well.
3560
3561 g++ has extended the template instantiation syntax outlined in the
3562 Working Paper to allow forward declaration of explicit instantiations
3563 and instantiation of the compiler support data for a template class
3564 (i.e. the vtable) without instantiating any of its members:
3565
3566 @example
3567 extern template int max (int, int);
3568 inline template class Foo<int>;
3569 @end example
3570
3571 @item
3572 Do nothing.  Pretend g++ does implement automatic instantiation
3573 management.  Code written for the Borland model will work fine, but
3574 each translation unit will contain instances of each of the templates it
3575 uses.  In a large program, this can lead to an unacceptable amount of code
3576 duplication.
3577
3578 @item
3579 Add @samp{#pragma interface} to all files containing template
3580 definitions.  For each of these files, add @samp{#pragma implementation
3581 "@var{filename}"} to the top of some @samp{.C} file which
3582 @samp{#include}s it.  Then compile everything with
3583 @samp{-fexternal-templates}.  The templates will then only be expanded
3584 in the translation unit which implements them (i.e. has a @samp{#pragma
3585 implementation} line for the file where they live); all other files will
3586 use external references.  If you're lucky, everything should work
3587 properly.  If you get undefined symbol errors, you need to make sure
3588 that each template instance which is used in the program is used in the
3589 file which implements that template.  If you don't have any use for a
3590 particular instance in that file, you can just instantiate it
3591 explicitly, using the syntax from the latest C++ working paper:
3592
3593 @example
3594 template class A<int>;
3595 template ostream& operator << (ostream&, const A<int>&);
3596 @end example
3597
3598 This strategy will work with code written for either model.  If you are
3599 using code written for the Cfront model, the file containing a class
3600 template and the file containing its member templates should be
3601 implemented in the same translation unit.
3602
3603 A slight variation on this approach is to instead use the flag
3604 @samp{-falt-external-templates}; this flag causes template
3605 instances to be emitted in the translation unit that implements the
3606 header where they are first instantiated, rather than the one which
3607 implements the file where the templates are defined.  This header must
3608 be the same in all translation units, or things are likely to break.
3609
3610 @xref{C++ Interface,,Declarations and Definitions in One Header}, for
3611 more discussion of these pragmas.
3612 @end enumerate
3613
3614 @node Bound member functions
3615 @section Extracting the function pointer from a bound pointer to member function
3616
3617 @cindex pmf
3618 @cindex pointer to member function
3619 @cindex bound pointer to member function
3620
3621 In C++, pointer to member functions (PMFs) are implemented using a wide
3622 pointer of sorts to handle all the possible call mechanisms; the PMF
3623 needs to store information about how to adjust the @samp{this} pointer,
3624 and if the function pointed to is virtual, where to find the vtable, and
3625 where in the vtable to look for the member function.  If you are using
3626 PMFs in an inner loop, you should really reconsider that decision.  If
3627 that is not an option, you can extract the pointer to the function that
3628 would be called for a given object/PMF pair and call it directly inside
3629 the inner loop, to save a bit of time.
3630
3631 Note that you will still be paying the penalty for the call through a
3632 function pointer; on most modern architectures, such a call defeats the
3633 branch prediction features of the CPU.  This is also true of normal
3634 virtual function calls.
3635
3636 The syntax for this extension is
3637
3638 @example
3639 extern A a;
3640 extern int (A::*fp)();
3641 typedef int (*fptr)(A *);
3642
3643 fptr p = (fptr)(a.*fp);
3644 @end example
3645
3646 You must specify @samp{-Wno-pmf-conversions} to use this extension.
3647
3648 @node C++ Signatures
3649 @section Type Abstraction using Signatures
3650
3651 @findex signature
3652 @cindex type abstraction, C++
3653 @cindex C++ type abstraction
3654 @cindex subtype polymorphism, C++
3655 @cindex C++ subtype polymorphism
3656 @cindex signatures, C++
3657 @cindex C++ signatures
3658
3659 In GNU C++, you can use the keyword @code{signature} to define a
3660 completely abstract class interface as a datatype.  You can connect this
3661 abstraction with actual classes using signature pointers.  If you want
3662 to use signatures, run the GNU compiler with the
3663 @samp{-fhandle-signatures} command-line option.  (With this option, the
3664 compiler reserves a second keyword @code{sigof} as well, for a future
3665 extension.)
3666
3667 Roughly, signatures are type abstractions or interfaces of classes.
3668 Some other languages have similar facilities.  C++ signatures are
3669 related to ML's signatures, Haskell's type classes, definition modules
3670 in Modula-2, interface modules in Modula-3, abstract types in Emerald,
3671 type modules in Trellis/Owl, categories in Scratchpad II, and types in
3672 POOL-I.  For a more detailed discussion of signatures, see
3673 @cite{Signatures: A Language Extension for Improving Type Abstraction and
3674 Subtype Polymorphism in C++}
3675 by @w{Gerald} Baumgartner and Vincent F. Russo (Tech report
3676 CSD--TR--95--051, Dept. of Computer Sciences, Purdue University,
3677 August 1995, a slightly improved version appeared in
3678 @emph{Software---Practice & Experience}, @b{25}(8), pp. 863--889,
3679 August 1995).  You can get the tech report by anonymous FTP from
3680 @code{ftp.cs.purdue.edu} in @file{pub/gb/Signature-design.ps.gz}.
3681
3682 Syntactically, a signature declaration is a collection of
3683 member function declarations and nested type declarations.
3684 For example, this signature declaration defines a new abstract type
3685 @code{S} with member functions @samp{int foo ()} and @samp{int bar (int)}:
3686
3687 @example
3688 signature S
3689 @{
3690   int foo ();
3691   int bar (int);
3692 @};
3693 @end example
3694
3695 Since signature types do not include implementation definitions, you
3696 cannot write an instance of a signature directly.  Instead, you can
3697 define a pointer to any class that contains the required interfaces as a
3698 @dfn{signature pointer}.  Such a class @dfn{implements} the signature
3699 type.
3700 @c Eventually signature references should work too.
3701
3702 To use a class as an implementation of @code{S}, you must ensure that
3703 the class has public member functions @samp{int foo ()} and @samp{int
3704 bar (int)}.  The class can have other member functions as well, public
3705 or not; as long as it offers what's declared in the signature, it is
3706 suitable as an implementation of that signature type.
3707
3708 For example, suppose that @code{C} is a class that meets the
3709 requirements of signature @code{S} (@code{C} @dfn{conforms to}
3710 @code{S}).  Then
3711
3712 @example
3713 C obj;
3714 S * p = &obj;
3715 @end example
3716
3717 @noindent
3718 defines a signature pointer @code{p} and initializes it to point to an
3719 object of type @code{C}.
3720 The member function call @w{@samp{int i = p->foo ();}}
3721 executes @samp{obj.foo ()}.
3722
3723 @cindex @code{signature} in C++, advantages
3724 Abstract virtual classes provide somewhat similar facilities in standard
3725 C++.  There are two main advantages to using signatures instead:
3726
3727 @enumerate
3728 @item
3729 Subtyping becomes independent from inheritance.  A class or signature
3730 type @code{T} is a subtype of a signature type @code{S} independent of
3731 any inheritance hierarchy as long as all the member functions declared
3732 in @code{S} are also found in @code{T}.  So you can define a subtype
3733 hierarchy that is completely independent from any inheritance
3734 (implementation) hierarchy, instead of being forced to use types that
3735 mirror the class inheritance hierarchy.
3736
3737 @item
3738 Signatures allow you to work with existing class hierarchies as
3739 implementations of a signature type.  If those class hierarchies are
3740 only available in compiled form, you're out of luck with abstract virtual
3741 classes, since an abstract virtual class cannot be retrofitted on top of
3742 existing class hierarchies.  So you would be required to write interface
3743 classes as subtypes of the abstract virtual class.
3744 @end enumerate
3745
3746 @cindex default implementation, signature member function
3747 @cindex signature member function default implementation
3748 There is one more detail about signatures.  A signature declaration can
3749 contain member function @emph{definitions} as well as member function
3750 declarations.  A signature member function with a full definition is
3751 called a @emph{default implementation}; classes need not contain that
3752 particular interface in order to conform.  For example, a
3753 class @code{C} can conform to the signature
3754
3755 @example
3756 signature T
3757 @{
3758   int f (int);
3759   int f0 () @{ return f (0); @};
3760 @};
3761 @end example
3762
3763 @noindent
3764 whether or not @code{C} implements the member function @samp{int f0 ()}.
3765 If you define @code{C::f0}, that definition takes precedence;
3766 otherwise, the default implementation @code{S::f0} applies.
3767
3768 @ignore
3769 There will be more support for signatures in the future.
3770 Add to this doc as the implementation grows.
3771 In particular, the following features are planned but not yet
3772 implemented:
3773 @itemize @bullet
3774 @item signature references,
3775 @item signature inheritance,
3776 @item the @code{sigof} construct for extracting the signature information
3777       of a class,
3778 @item views for renaming member functions when matching a class type
3779       with a signature type,
3780 @item specifying exceptions with signature member functions, and
3781 @item signature templates.
3782 @end itemize
3783 This list is roughly in the order in which we intend to implement
3784 them.  Watch this space for updates.
3785 @end ignore