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