OSDN Git Service

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