2001-01-23 Alexandre Petit-Bianco <apbianco@cygnus.com>
[official-gcc.git] / gcc / extend.texi
blob51a8ff040e5b4b646e298457e83df3a644931e02
1 @c Copyright (C) 1988,89,92,93,94,96,98,99,2000,01 Free Software Foundation, Inc.
2 @c This is part of the GCC manual.
3 @c For copying conditions, see the file gcc.texi.
5 @node C Extensions
6 @chapter Extensions to the C Language Family
7 @cindex extensions, C language
8 @cindex C language extensions
10 GNU C provides several language features not found in ISO 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.
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++.
20 @c FIXME: document clearly which features are in ISO C99, but also
21 @c accepted as extensions for -std=gnu89 and possibly for C++.
22 @c See PR other/930.
24 @c FIXME: the documentation for preprocessor extensions here is out of
25 @c date.  See PR other/928.
27 @c The only difference between the two versions of this menu is that the
28 @c version for clear INTERNALS has an extra node, "Constraints" (which
29 @c appears in a separate chapter in the other version of the manual).
30 @ifset INTERNALS
31 @menu
32 * Statement Exprs::     Putting statements and declarations inside expressions.
33 * Local Labels::        Labels local to a statement-expression.
34 * Labels as Values::    Getting pointers to labels, and computed gotos.
35 * Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
36 * Constructing Calls::  Dispatching a call to another function.
37 * Naming Types::        Giving a name to the type of some expression.
38 * Typeof::              @code{typeof}: referring to the type of an expression.
39 * Lvalues::             Using @samp{?:}, @samp{,} and casts in lvalues.
40 * Conditionals::        Omitting the middle operand of a @samp{?:} expression.
41 * Long Long::           Double-word integers---@code{long long int}.
42 * Complex::             Data types for complex numbers.
43 * Hex Floats::          Hexadecimal floating-point constants.
44 * Zero Length::         Zero-length arrays.
45 * Variable Length::     Arrays whose length is computed at run time.
46 * Variadic Macros::     Macros with a variable number of arguments.
47 * Escaped Newlines::    Slightly looser rules for escaped newlines.
48 * Multi-line Strings::  String literals with embedded newlines.
49 * Subscripting::        Any array can be subscripted, even if not an lvalue.
50 * Pointer Arith::       Arithmetic on @code{void}-pointers and function pointers.
51 * Initializers::        Non-constant initializers.
52 * Constructors::        Constructor expressions give structures, unions
53                          or arrays as values.
54 * Labeled Elements::    Labeling elements of initializers.
55 * Cast to Union::       Casting to union type from any member of the union.
56 * Case Ranges::         `case 1 ... 9' and such.
57 * Function Attributes:: Declaring that functions have no side effects,
58                          or that they can never return.
59 * Function Prototypes:: Prototype declarations and old-style definitions.
60 * C++ Comments::        C++ comments are recognized.
61 * Dollar Signs::        Dollar sign is allowed in identifiers.
62 * Character Escapes::   @samp{\e} stands for the character @key{ESC}.
63 * Variable Attributes:: Specifying attributes of variables.
64 * Type Attributes::     Specifying attributes of types.
65 * Alignment::           Inquiring about the alignment of a type or variable.
66 * Inline::              Defining inline functions (as fast as macros).
67 * Extended Asm::        Assembler instructions with C expressions as operands.
68                          (With them you can define ``built-in'' functions.)
69 * Asm Labels::          Specifying the assembler name to use for a C symbol.
70 * Explicit Reg Vars::   Defining variables residing in specified registers.
71 * Alternate Keywords::  @code{__const__}, @code{__asm__}, etc., for header files.
72 * Incomplete Enums::    @code{enum foo;}, with details to follow.
73 * Function Names::      Printable strings which are the name of the current
74                          function.
75 * Return Address::      Getting the return or frame address of a function.
76 * Other Builtins::      Other built-in functions.
77 @end menu
78 @end ifset
79 @ifclear INTERNALS
80 @menu
81 * Statement Exprs::     Putting statements and declarations inside expressions.
82 * Local Labels::        Labels local to a statement-expression.
83 * Labels as Values::    Getting pointers to labels, and computed gotos.
84 * Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
85 * Constructing Calls::  Dispatching a call to another function.
86 * Naming Types::        Giving a name to the type of some expression.
87 * Typeof::              @code{typeof}: referring to the type of an expression.
88 * Lvalues::             Using @samp{?:}, @samp{,} and casts in lvalues.
89 * Conditionals::        Omitting the middle operand of a @samp{?:} expression.
90 * Long Long::           Double-word integers---@code{long long int}.
91 * Complex::             Data types for complex numbers.
92 * Hex Floats::          Hexadecimal floating-point constants.
93 * Zero Length::         Zero-length arrays.
94 * Variable Length::     Arrays whose length is computed at run time.
95 * Variadic Macros::     Macros with a variable number of arguments.
96 * Escaped Newlines::    Slightly looser rules for escaped newlines.
97 * Multi-line Strings::  String literals with embedded newlines.
98 * Subscripting::        Any array can be subscripted, even if not an lvalue.
99 * Pointer Arith::       Arithmetic on @code{void}-pointers and function pointers.
100 * Initializers::        Non-constant initializers.
101 * Constructors::        Constructor expressions give structures, unions
102                          or arrays as values.
103 * Labeled Elements::    Labeling elements of initializers.
104 * Cast to Union::       Casting to union type from any member of the union.
105 * Case Ranges::         `case 1 ... 9' and such.
106 * Function Attributes:: Declaring that functions have no side effects,
107                          or that they can never return.
108 * Function Prototypes:: Prototype declarations and old-style definitions.
109 * C++ Comments::        C++ comments are recognized.
110 * Dollar Signs::        Dollar sign is allowed in identifiers.
111 * Character Escapes::   @samp{\e} stands for the character @key{ESC}.
112 * Variable Attributes:: Specifying attributes of variables.
113 * Type Attributes::     Specifying attributes of types.
114 * Alignment::           Inquiring about the alignment of a type or variable.
115 * Inline::              Defining inline functions (as fast as macros).
116 * Extended Asm::        Assembler instructions with C expressions as operands.
117                          (With them you can define ``built-in'' functions.)
118 * Constraints::         Constraints for asm operands
119 * Asm Labels::          Specifying the assembler name to use for a C symbol.
120 * Explicit Reg Vars::   Defining variables residing in specified registers.
121 * Alternate Keywords::  @code{__const__}, @code{__asm__}, etc., for header files.
122 * Incomplete Enums::    @code{enum foo;}, with details to follow.
123 * Function Names::      Printable strings which are the name of the current
124                          function.
125 * Return Address::      Getting the return or frame address of a function.
126 * Other Builtins::      Other built-in functions.
127 @end menu
128 @end ifclear
130 @node Statement Exprs
131 @section Statements and Declarations in Expressions
132 @cindex statements inside expressions
133 @cindex declarations inside expressions
134 @cindex expressions containing statements
135 @cindex macros, statements in expressions
137 @c the above section title wrapped and causes an underfull hbox.. i
138 @c changed it from "within" to "in". --mew 4feb93
140 A compound statement enclosed in parentheses may appear as an expression
141 in GNU C.  This allows you to use loops, switches, and local variables
142 within an expression.
144 Recall that a compound statement is a sequence of statements surrounded
145 by braces; in this construct, parentheses go around the braces.  For
146 example:
148 @example
149 (@{ int y = foo (); int z;
150    if (y > 0) z = y;
151    else z = - y;
152    z; @})
153 @end example
155 @noindent
156 is a valid (though slightly more complex than necessary) expression
157 for the absolute value of @code{foo ()}.
159 The last thing in the compound statement should be an expression
160 followed by a semicolon; the value of this subexpression serves as the
161 value of the entire construct.  (If you use some other kind of statement
162 last within the braces, the construct has type @code{void}, and thus
163 effectively no value.)
165 This feature is especially useful in making macro definitions ``safe'' (so
166 that they evaluate each operand exactly once).  For example, the
167 ``maximum'' function is commonly defined as a macro in standard C as
168 follows:
170 @example
171 #define max(a,b) ((a) > (b) ? (a) : (b))
172 @end example
174 @noindent
175 @cindex side effects, macro argument
176 But this definition computes either @var{a} or @var{b} twice, with bad
177 results if the operand has side effects.  In GNU C, if you know the
178 type of the operands (here let's assume @code{int}), you can define
179 the macro safely as follows:
181 @example
182 #define maxint(a,b) \
183   (@{int _a = (a), _b = (b); _a > _b ? _a : _b; @})
184 @end example
186 Embedded statements are not allowed in constant expressions, such as
187 the value of an enumeration constant, the width of a bit field, or
188 the initial value of a static variable.
190 If you don't know the type of the operand, you can still do this, but you
191 must use @code{typeof} (@pxref{Typeof}) or type naming (@pxref{Naming
192 Types}).
194 Statement expressions are not supported fully in G++, and their fate
195 there is unclear.  (It is possible that they will become fully supported
196 at some point, or that they will be deprecated, or that the bugs that
197 are present will continue to exist indefinitely.)  Presently, statement
198 expressions do not work well as default arguments. 
200 In addition, there are semantic issues with statement-expressions in
201 C++.  If you try to use statement-expressions instead of inline
202 functions in C++, you may be surprised at the way object destruction is
203 handled.  For example:
205 @example
206 #define foo(a)  (@{int b = (a); b + 3; @})
207 @end example
209 @noindent
210 does not work the same way as:
212 @example
213 inline int foo(int a) @{ int b = a; return b + 3; @}
214 @end example
216 @noindent
217 In particular, if the expression passed into @code{foo} involves the
218 creation of temporaries, the destructors for those temporaries will be
219 run earlier in the case of the macro than in the case of the function.
221 These considerations mean that it is probably a bad idea to use
222 statement-expressions of this form in header files that are designed to
223 work with C++.  (Note that some versions of the GNU C Library contained
224 header files using statement-expression that lead to precisely this
225 bug.)
227 @node Local Labels
228 @section Locally Declared Labels
229 @cindex local labels
230 @cindex macros, local labels
232 Each statement expression is a scope in which @dfn{local labels} can be
233 declared.  A local label is simply an identifier; you can jump to it
234 with an ordinary @code{goto} statement, but only from within the
235 statement expression it belongs to.
237 A local label declaration looks like this:
239 @example
240 __label__ @var{label};
241 @end example
243 @noindent
246 @example
247 __label__ @var{label1}, @var{label2}, @dots{};
248 @end example
250 Local label declarations must come at the beginning of the statement
251 expression, right after the @samp{(@{}, before any ordinary
252 declarations.
254 The label declaration defines the label @emph{name}, but does not define
255 the label itself.  You must do this in the usual way, with
256 @code{@var{label}:}, within the statements of the statement expression.
258 The local label feature is useful because statement expressions are
259 often used in macros.  If the macro contains nested loops, a @code{goto}
260 can be useful for breaking out of them.  However, an ordinary label
261 whose scope is the whole function cannot be used: if the macro can be
262 expanded several times in one function, the label will be multiply
263 defined in that function.  A local label avoids this problem.  For
264 example:
266 @example
267 #define SEARCH(array, target)                     \
268 (@{                                               \
269   __label__ found;                                \
270   typeof (target) _SEARCH_target = (target);      \
271   typeof (*(array)) *_SEARCH_array = (array);     \
272   int i, j;                                       \
273   int value;                                      \
274   for (i = 0; i < max; i++)                       \
275     for (j = 0; j < max; j++)                     \
276       if (_SEARCH_array[i][j] == _SEARCH_target)  \
277         @{ value = i; goto found; @}              \
278   value = -1;                                     \
279  found:                                           \
280   value;                                          \
282 @end example
284 @node Labels as Values
285 @section Labels as Values
286 @cindex labels as values
287 @cindex computed gotos
288 @cindex goto with computed label
289 @cindex address of a label
291 You can get the address of a label defined in the current function
292 (or a containing function) with the unary operator @samp{&&}.  The
293 value has type @code{void *}.  This value is a constant and can be used
294 wherever a constant of that type is valid.  For example:
296 @example
297 void *ptr;
298 @dots{}
299 ptr = &&foo;
300 @end example
302 To use these values, you need to be able to jump to one.  This is done
303 with the computed goto statement@footnote{The analogous feature in
304 Fortran is called an assigned goto, but that name seems inappropriate in
305 C, where one can do more than simply store label addresses in label
306 variables.}, @code{goto *@var{exp};}.  For example,
308 @example
309 goto *ptr;
310 @end example
312 @noindent
313 Any expression of type @code{void *} is allowed.
315 One way of using these constants is in initializing a static array that
316 will serve as a jump table:
318 @example
319 static void *array[] = @{ &&foo, &&bar, &&hack @};
320 @end example
322 Then you can select a label with indexing, like this:
324 @example
325 goto *array[i];
326 @end example
328 @noindent
329 Note that this does not check whether the subscript is in bounds---array
330 indexing in C never does that.
332 Such an array of label values serves a purpose much like that of the
333 @code{switch} statement.  The @code{switch} statement is cleaner, so
334 use that rather than an array unless the problem does not fit a
335 @code{switch} statement very well.
337 Another use of label values is in an interpreter for threaded code.
338 The labels within the interpreter function can be stored in the
339 threaded code for super-fast dispatching.
341 You may not use this mechanism to jump to code in a different function. 
342 If you do that, totally unpredictable things will happen.  The best way to
343 avoid this is to store the label address only in automatic variables and
344 never pass it as an argument.
346 An alternate way to write the above example is
348 @example
349 static const int array[] = @{ &&foo - &&foo, &&bar - &&foo, &&hack - &&foo @};
350 goto *(&&foo + array[i]);
351 @end example
353 @noindent
354 This is more friendly to code living in shared libraries, as it reduces
355 the number of dynamic relocations that are needed, and by consequence,
356 allows the data to be read-only.
358 @node Nested Functions
359 @section Nested Functions
360 @cindex nested functions
361 @cindex downward funargs
362 @cindex thunks
364 A @dfn{nested function} is a function defined inside another function.
365 (Nested functions are not supported for GNU C++.)  The nested function's
366 name is local to the block where it is defined.  For example, here we
367 define a nested function named @code{square}, and call it twice:
369 @example
370 @group
371 foo (double a, double b)
373   double square (double z) @{ return z * z; @}
375   return square (a) + square (b);
377 @end group
378 @end example
380 The nested function can access all the variables of the containing
381 function that are visible at the point of its definition.  This is
382 called @dfn{lexical scoping}.  For example, here we show a nested
383 function which uses an inherited variable named @code{offset}:
385 @example
386 bar (int *array, int offset, int size)
388   int access (int *array, int index)
389     @{ return array[index + offset]; @}
390   int i;
391   @dots{}
392   for (i = 0; i < size; i++)
393     @dots{} access (array, i) @dots{}
395 @end example
397 Nested function definitions are permitted within functions in the places
398 where variable definitions are allowed; that is, in any block, before
399 the first statement in the block.
401 It is possible to call the nested function from outside the scope of its
402 name by storing its address or passing the address to another function:
404 @example
405 hack (int *array, int size)
407   void store (int index, int value)
408     @{ array[index] = value; @}
410   intermediate (store, size);
412 @end example
414 Here, the function @code{intermediate} receives the address of
415 @code{store} as an argument.  If @code{intermediate} calls @code{store},
416 the arguments given to @code{store} are used to store into @code{array}.
417 But this technique works only so long as the containing function
418 (@code{hack}, in this example) does not exit.
420 If you try to call the nested function through its address after the
421 containing function has exited, all hell will break loose.  If you try
422 to call it after a containing scope level has exited, and if it refers
423 to some of the variables that are no longer in scope, you may be lucky,
424 but it's not wise to take the risk.  If, however, the nested function
425 does not refer to anything that has gone out of scope, you should be
426 safe.
428 GNU CC implements taking the address of a nested function using a
429 technique called @dfn{trampolines}.   A paper describing them is
430 available as @uref{http://people.debian.org/~karlheg/Usenix88-lexic.pdf}.
432 A nested function can jump to a label inherited from a containing
433 function, provided the label was explicitly declared in the containing
434 function (@pxref{Local Labels}).  Such a jump returns instantly to the
435 containing function, exiting the nested function which did the
436 @code{goto} and any intermediate functions as well.  Here is an example:
438 @example
439 @group
440 bar (int *array, int offset, int size)
442   __label__ failure;
443   int access (int *array, int index)
444     @{
445       if (index > size)
446         goto failure;
447       return array[index + offset];
448     @}
449   int i;
450   @dots{}
451   for (i = 0; i < size; i++)
452     @dots{} access (array, i) @dots{}
453   @dots{}
454   return 0;
456  /* @r{Control comes here from @code{access}
457     if it detects an error.}  */
458  failure:
459   return -1;
461 @end group
462 @end example
464 A nested function always has internal linkage.  Declaring one with
465 @code{extern} is erroneous.  If you need to declare the nested function
466 before its definition, use @code{auto} (which is otherwise meaningless
467 for function declarations).
469 @example
470 bar (int *array, int offset, int size)
472   __label__ failure;
473   auto int access (int *, int);
474   @dots{}
475   int access (int *array, int index)
476     @{
477       if (index > size)
478         goto failure;
479       return array[index + offset];
480     @}
481   @dots{}
483 @end example
485 @node Constructing Calls
486 @section Constructing Function Calls
487 @cindex constructing calls
488 @cindex forwarding calls
490 Using the built-in functions described below, you can record
491 the arguments a function received, and call another function
492 with the same arguments, without knowing the number or types
493 of the arguments.
495 You can also record the return value of that function call,
496 and later return that value, without knowing what data type
497 the function tried to return (as long as your caller expects
498 that data type).
500 @table @code
501 @findex __builtin_apply_args
502 @item __builtin_apply_args ()
503 This built-in function returns a pointer of type @code{void *} to data
504 describing how to perform a call with the same arguments as were passed
505 to the current function.
507 The function saves the arg pointer register, structure value address,
508 and all registers that might be used to pass arguments to a function
509 into a block of memory allocated on the stack.  Then it returns the
510 address of that block.
512 @findex __builtin_apply
513 @item __builtin_apply (@var{function}, @var{arguments}, @var{size})
514 This built-in function invokes @var{function} (type @code{void (*)()})
515 with a copy of the parameters described by @var{arguments} (type
516 @code{void *}) and @var{size} (type @code{int}).
518 The value of @var{arguments} should be the value returned by
519 @code{__builtin_apply_args}.  The argument @var{size} specifies the size
520 of the stack argument data, in bytes.
522 This function returns a pointer of type @code{void *} to data describing
523 how to return whatever value was returned by @var{function}.  The data
524 is saved in a block of memory allocated on the stack.
526 It is not always simple to compute the proper value for @var{size}.  The
527 value is used by @code{__builtin_apply} to compute the amount of data
528 that should be pushed on the stack and copied from the incoming argument
529 area.
531 @findex __builtin_return
532 @item __builtin_return (@var{result})
533 This built-in function returns the value described by @var{result} from
534 the containing function.  You should specify, for @var{result}, a value
535 returned by @code{__builtin_apply}.
536 @end table
538 @node Naming Types
539 @section Naming an Expression's Type
540 @cindex naming types
542 You can give a name to the type of an expression using a @code{typedef}
543 declaration with an initializer.  Here is how to define @var{name} as a
544 type name for the type of @var{exp}:
546 @example
547 typedef @var{name} = @var{exp};
548 @end example
550 This is useful in conjunction with the statements-within-expressions
551 feature.  Here is how the two together can be used to define a safe
552 ``maximum'' macro that operates on any arithmetic type:
554 @example
555 #define max(a,b) \
556   (@{typedef _ta = (a), _tb = (b);  \
557     _ta _a = (a); _tb _b = (b);     \
558     _a > _b ? _a : _b; @})
559 @end example
561 @cindex underscores in variables in macros
562 @cindex @samp{_} in variables in macros
563 @cindex local variables in macros
564 @cindex variables, local, in macros
565 @cindex macros, local variables in
567 The reason for using names that start with underscores for the local
568 variables is to avoid conflicts with variable names that occur within the
569 expressions that are substituted for @code{a} and @code{b}.  Eventually we
570 hope to design a new form of declaration syntax that allows you to declare
571 variables whose scopes start only after their initializers; this will be a
572 more reliable way to prevent such conflicts.
574 @node Typeof
575 @section Referring to a Type with @code{typeof}
576 @findex typeof
577 @findex sizeof
578 @cindex macros, types of arguments
580 Another way to refer to the type of an expression is with @code{typeof}.
581 The syntax of using of this keyword looks like @code{sizeof}, but the
582 construct acts semantically like a type name defined with @code{typedef}.
584 There are two ways of writing the argument to @code{typeof}: with an
585 expression or with a type.  Here is an example with an expression:
587 @example
588 typeof (x[0](1))
589 @end example
591 @noindent
592 This assumes that @code{x} is an array of pointers to functions;
593 the type described is that of the values of the functions.
595 Here is an example with a typename as the argument:
597 @example
598 typeof (int *)
599 @end example
601 @noindent
602 Here the type described is that of pointers to @code{int}.
604 If you are writing a header file that must work when included in ISO C
605 programs, write @code{__typeof__} instead of @code{typeof}.
606 @xref{Alternate Keywords}.
608 A @code{typeof}-construct can be used anywhere a typedef name could be
609 used.  For example, you can use it in a declaration, in a cast, or inside
610 of @code{sizeof} or @code{typeof}.
612 @itemize @bullet
613 @item
614 This declares @code{y} with the type of what @code{x} points to.
616 @example
617 typeof (*x) y;
618 @end example
620 @item
621 This declares @code{y} as an array of such values.
623 @example
624 typeof (*x) y[4];
625 @end example
627 @item
628 This declares @code{y} as an array of pointers to characters:
630 @example
631 typeof (typeof (char *)[4]) y;
632 @end example
634 @noindent
635 It is equivalent to the following traditional C declaration:
637 @example
638 char *y[4];
639 @end example
641 To see the meaning of the declaration using @code{typeof}, and why it
642 might be a useful way to write, let's rewrite it with these macros:
644 @example
645 #define pointer(T)  typeof(T *)
646 #define array(T, N) typeof(T [N])
647 @end example
649 @noindent
650 Now the declaration can be rewritten this way:
652 @example
653 array (pointer (char), 4) y;
654 @end example
656 @noindent
657 Thus, @code{array (pointer (char), 4)} is the type of arrays of 4
658 pointers to @code{char}.
659 @end itemize
661 @node Lvalues
662 @section Generalized Lvalues
663 @cindex compound expressions as lvalues
664 @cindex expressions, compound, as lvalues
665 @cindex conditional expressions as lvalues
666 @cindex expressions, conditional, as lvalues
667 @cindex casts as lvalues
668 @cindex generalized lvalues
669 @cindex lvalues, generalized
670 @cindex extensions, @code{?:}
671 @cindex @code{?:} extensions
672 Compound expressions, conditional expressions and casts are allowed as
673 lvalues provided their operands are lvalues.  This means that you can take
674 their addresses or store values into them.
676 Standard C++ allows compound expressions and conditional expressions as
677 lvalues, and permits casts to reference type, so use of this extension
678 is deprecated for C++ code.
680 For example, a compound expression can be assigned, provided the last
681 expression in the sequence is an lvalue.  These two expressions are
682 equivalent:
684 @example
685 (a, b) += 5
686 a, (b += 5)
687 @end example
689 Similarly, the address of the compound expression can be taken.  These two
690 expressions are equivalent:
692 @example
693 &(a, b)
694 a, &b
695 @end example
697 A conditional expression is a valid lvalue if its type is not void and the
698 true and false branches are both valid lvalues.  For example, these two
699 expressions are equivalent:
701 @example
702 (a ? b : c) = 5
703 (a ? b = 5 : (c = 5))
704 @end example
706 A cast is a valid lvalue if its operand is an lvalue.  A simple
707 assignment whose left-hand side is a cast works by converting the
708 right-hand side first to the specified type, then to the type of the
709 inner left-hand side expression.  After this is stored, the value is
710 converted back to the specified type to become the value of the
711 assignment.  Thus, if @code{a} has type @code{char *}, the following two
712 expressions are equivalent:
714 @example
715 (int)a = 5
716 (int)(a = (char *)(int)5)
717 @end example
719 An assignment-with-arithmetic operation such as @samp{+=} applied to a cast
720 performs the arithmetic using the type resulting from the cast, and then
721 continues as in the previous case.  Therefore, these two expressions are
722 equivalent:
724 @example
725 (int)a += 5
726 (int)(a = (char *)(int) ((int)a + 5))
727 @end example
729 You cannot take the address of an lvalue cast, because the use of its
730 address would not work out coherently.  Suppose that @code{&(int)f} were
731 permitted, where @code{f} has type @code{float}.  Then the following
732 statement would try to store an integer bit-pattern where a floating
733 point number belongs:
735 @example
736 *&(int)f = 1;
737 @end example
739 This is quite different from what @code{(int)f = 1} would do---that
740 would convert 1 to floating point and store it.  Rather than cause this
741 inconsistency, we think it is better to prohibit use of @samp{&} on a cast.
743 If you really do want an @code{int *} pointer with the address of
744 @code{f}, you can simply write @code{(int *)&f}.
746 @node Conditionals
747 @section Conditionals with Omitted Operands
748 @cindex conditional expressions, extensions
749 @cindex omitted middle-operands
750 @cindex middle-operands, omitted
751 @cindex extensions, @code{?:}
752 @cindex @code{?:} extensions
754 The middle operand in a conditional expression may be omitted.  Then
755 if the first operand is nonzero, its value is the value of the conditional
756 expression.
758 Therefore, the expression
760 @example
761 x ? : y
762 @end example
764 @noindent
765 has the value of @code{x} if that is nonzero; otherwise, the value of
766 @code{y}.
768 This example is perfectly equivalent to
770 @example
771 x ? x : y
772 @end example
774 @cindex side effect in ?:
775 @cindex ?: side effect
776 @noindent
777 In this simple case, the ability to omit the middle operand is not
778 especially useful.  When it becomes useful is when the first operand does,
779 or may (if it is a macro argument), contain a side effect.  Then repeating
780 the operand in the middle would perform the side effect twice.  Omitting
781 the middle operand uses the value already computed without the undesirable
782 effects of recomputing it.
784 @node Long Long
785 @section Double-Word Integers
786 @cindex @code{long long} data types
787 @cindex double-word arithmetic
788 @cindex multiprecision arithmetic
790 GNU C supports data types for integers that are twice as long as
791 @code{int}.  Simply write @code{long long int} for a signed integer, or
792 @code{unsigned long long int} for an unsigned integer.  To make an
793 integer constant of type @code{long long int}, add the suffix @code{LL}
794 to the integer.  To make an integer constant of type @code{unsigned long
795 long int}, add the suffix @code{ULL} to the integer.
797 You can use these types in arithmetic like any other integer types.
798 Addition, subtraction, and bitwise boolean operations on these types
799 are open-coded on all types of machines.  Multiplication is open-coded
800 if the machine supports fullword-to-doubleword a widening multiply
801 instruction.  Division and shifts are open-coded only on machines that
802 provide special support.  The operations that are not open-coded use
803 special library routines that come with GNU CC.
805 There may be pitfalls when you use @code{long long} types for function
806 arguments, unless you declare function prototypes.  If a function
807 expects type @code{int} for its argument, and you pass a value of type
808 @code{long long int}, confusion will result because the caller and the
809 subroutine will disagree about the number of bytes for the argument.
810 Likewise, if the function expects @code{long long int} and you pass
811 @code{int}.  The best way to avoid such problems is to use prototypes.
813 @node Complex
814 @section Complex Numbers
815 @cindex complex numbers
817 GNU C supports complex data types.  You can declare both complex integer
818 types and complex floating types, using the keyword @code{__complex__}.
820 For example, @samp{__complex__ double x;} declares @code{x} as a
821 variable whose real part and imaginary part are both of type
822 @code{double}.  @samp{__complex__ short int y;} declares @code{y} to
823 have real and imaginary parts of type @code{short int}; this is not
824 likely to be useful, but it shows that the set of complex types is
825 complete.
827 To write a constant with a complex data type, use the suffix @samp{i} or
828 @samp{j} (either one; they are equivalent).  For example, @code{2.5fi}
829 has type @code{__complex__ float} and @code{3i} has type
830 @code{__complex__ int}.  Such a constant always has a pure imaginary
831 value, but you can form any complex value you like by adding one to a
832 real constant.
834 To extract the real part of a complex-valued expression @var{exp}, write
835 @code{__real__ @var{exp}}.  Likewise, use @code{__imag__} to
836 extract the imaginary part.
838 The operator @samp{~} performs complex conjugation when used on a value
839 with a complex type.
841 GNU CC can allocate complex automatic variables in a noncontiguous
842 fashion; it's even possible for the real part to be in a register while
843 the imaginary part is on the stack (or vice-versa).  None of the
844 supported debugging info formats has a way to represent noncontiguous
845 allocation like this, so GNU CC describes a noncontiguous complex
846 variable as if it were two separate variables of noncomplex type.
847 If the variable's actual name is @code{foo}, the two fictitious
848 variables are named @code{foo$real} and @code{foo$imag}.  You can
849 examine and set these two fictitious variables with your debugger.
851 A future version of GDB will know how to recognize such pairs and treat
852 them as a single variable with a complex type.
854 @node Hex Floats
855 @section Hex Floats
856 @cindex hex floats
858 GNU CC recognizes floating-point numbers written not only in the usual
859 decimal notation, such as @code{1.55e1}, but also numbers such as
860 @code{0x1.fp3} written in hexadecimal format.  In that format the
861 @code{0x} hex introducer and the @code{p} or @code{P} exponent field are
862 mandatory.  The exponent is a decimal number that indicates the power of
863 2 by which the significant part will be multiplied.  Thus @code{0x1.f} is
864 1 15/16, @code{p3} multiplies it by 8, and the value of @code{0x1.fp3}
865 is the same as @code{1.55e1}.
867 Unlike for floating-point numbers in the decimal notation the exponent
868 is always required in the hexadecimal notation.  Otherwise the compiler
869 would not be able to resolve the ambiguity of, e.g., @code{0x1.f}.  This
870 could mean @code{1.0f} or @code{1.9375} since @code{f} is also the
871 extension for floating-point constants of type @code{float}.
873 @node Zero Length
874 @section Arrays of Length Zero
875 @cindex arrays of length zero
876 @cindex zero-length arrays
877 @cindex length-zero arrays
878 @cindex flexible array members
880 Zero-length arrays are allowed in GNU C.  They are very useful as the
881 last element of a structure which is really a header for a variable-length
882 object:
884 @example
885 struct line @{
886   int length;
887   char contents[0];
890 struct line *thisline = (struct line *)
891   malloc (sizeof (struct line) + this_length);
892 thisline->length = this_length;
893 @end example
895 In ISO C89, you would have to give @code{contents} a length of 1, which
896 means either you waste space or complicate the argument to @code{malloc}.
898 In ISO C99, you would use a @dfn{flexible array member}, which is 
899 slightly different in syntax and semantics:
901 @itemize @bullet
902 @item
903 Flexible array members are written as @code{contents[]} without
904 the @code{0}.
906 @item
907 Flexible array members have incomplete type, and so the @code{sizeof}
908 operator may not be applied.  As a quirk of the original implementation
909 of zero-length arrays, @code{sizeof} evaluates to zero.
911 @item
912 Flexible array members may only appear as the last member of a
913 @code{struct} that is otherwise non-empty.  GCC currently allows 
914 zero-length arrays anywhere.  You may encounter problems, however,
915 defining structures containing only a zero-length array.  Such usage
916 is deprecated, and we recommend using zero-length arrays only in
917 places in which flexible array members would be allowed.
918 @end itemize
920 GCC versions before 3.0 allowed zero-length arrays to be statically
921 initialized.  In addition to those cases that were useful, it also
922 allowed initializations in situations that would corrupt later data.
923 Non-empty initialization of zero-length arrays is now deprecated.
925 Instead GCC allows static initialization of flexible array members.
926 This is equivalent to defining a new structure containing the original
927 structure followed by an array of sufficient size to contain the data.
928 I.e. in the following, @code{f1} is constructed as if it were declared
929 like @code{f2}.
931 @example
932 struct f1 @{
933   int x; int y[];
934 @} f1 = @{ 1, @{ 2, 3, 4 @} @};
936 struct f2 @{
937   struct f1 f1; int data[3];
938 @} f2 = @{ @{ 1 @}, @{ 2, 3, 4 @} @};
939 @end example
941 @noindent
942 The convenience of this extension is that @code{f1} has the desired
943 type, eliminating the need to consistently refer to @code{f2.f1}.
945 This has symmetry with normal static arrays, in that an array of
946 unknown size is also written with @code{[]}.
948 Of course, this extension only makes sense if the extra data comes at
949 the end of a top-level object, as otherwise we would be overwriting
950 data at subsequent offsets.  To avoid undue complication and confusion
951 with initialization of deeply nested arrays, we simply disallow any
952 non-empty initialization except when the structure is the top-level
953 object.  For example:
955 @example
956 struct foo @{ int x; int y[]; @};
957 struct bar @{ struct foo z; @};
959 struct foo a = @{ 1, @{ 2, 3, 4 @} @};        // Legal.
960 struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @};    // Illegal.
961 struct bar c = @{ @{ 1, @{ @} @} @};            // Legal.
962 struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @};  // Illegal.
963 @end example
965 @node Variable Length
966 @section Arrays of Variable Length
967 @cindex variable-length arrays
968 @cindex arrays of variable length
970 Variable-length automatic arrays are allowed in GNU C.  These arrays are
971 declared like any other automatic arrays, but with a length that is not
972 a constant expression.  The storage is allocated at the point of
973 declaration and deallocated when the brace-level is exited.  For
974 example:
976 @example
977 FILE *
978 concat_fopen (char *s1, char *s2, char *mode)
980   char str[strlen (s1) + strlen (s2) + 1];
981   strcpy (str, s1);
982   strcat (str, s2);
983   return fopen (str, mode);
985 @end example
987 @cindex scope of a variable length array
988 @cindex variable-length array scope
989 @cindex deallocating variable length arrays
990 Jumping or breaking out of the scope of the array name deallocates the
991 storage.  Jumping into the scope is not allowed; you get an error
992 message for it.
994 @cindex @code{alloca} vs variable-length arrays
995 You can use the function @code{alloca} to get an effect much like
996 variable-length arrays.  The function @code{alloca} is available in
997 many other C implementations (but not in all).  On the other hand,
998 variable-length arrays are more elegant.
1000 There are other differences between these two methods.  Space allocated
1001 with @code{alloca} exists until the containing @emph{function} returns.
1002 The space for a variable-length array is deallocated as soon as the array
1003 name's scope ends.  (If you use both variable-length arrays and
1004 @code{alloca} in the same function, deallocation of a variable-length array
1005 will also deallocate anything more recently allocated with @code{alloca}.)
1007 You can also use variable-length arrays as arguments to functions:
1009 @example
1010 struct entry
1011 tester (int len, char data[len][len])
1013   @dots{}
1015 @end example
1017 The length of an array is computed once when the storage is allocated
1018 and is remembered for the scope of the array in case you access it with
1019 @code{sizeof}.
1021 If you want to pass the array first and the length afterward, you can
1022 use a forward declaration in the parameter list---another GNU extension.
1024 @example
1025 struct entry
1026 tester (int len; char data[len][len], int len)
1028   @dots{}
1030 @end example
1032 @cindex parameter forward declaration
1033 The @samp{int len} before the semicolon is a @dfn{parameter forward
1034 declaration}, and it serves the purpose of making the name @code{len}
1035 known when the declaration of @code{data} is parsed.
1037 You can write any number of such parameter forward declarations in the
1038 parameter list.  They can be separated by commas or semicolons, but the
1039 last one must end with a semicolon, which is followed by the ``real''
1040 parameter declarations.  Each forward declaration must match a ``real''
1041 declaration in parameter name and data type.
1043 @node Variadic Macros
1044 @section Macros with a Variable Number of Arguments.
1045 @cindex variable number of arguments
1046 @cindex macro with variable arguments
1047 @cindex rest argument (in macro)
1048 @cindex variadic macros
1050 In the ISO C standard of 1999, a macro can be declared to accept a
1051 variable number of arguments much as a function can.  The syntax for
1052 defining the macro is similar to that of a function.  Here is an
1053 example:
1055 @example
1056 #define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)
1057 @end example
1059 Here @samp{@dots{}} is a @dfn{variable argument}.  In the invocation of
1060 such a macro, it represents the zero or more tokens until the closing
1061 parenthesis that ends the invocation, including any commas.  This set of
1062 tokens replaces the identifier @code{__VA_ARGS__} in the macro body
1063 wherever it appears.  See the CPP manual for more information.
1065 GCC has long supported variadic macros, and used a different syntax that
1066 allowed you to give a name to the variable arguments just like any other
1067 argument.  Here is an example:
1069 @example
1070 #define debug(format, args...) fprintf (stderr, format, args)
1071 @end example
1073 This is in all ways equivalent to the ISO C example above, but arguably
1074 more readable and descriptive.
1076 GNU CPP has two further variadic macro extensions, and permits them to
1077 be used with either of the above forms of macro definition.
1079 In standard C, you are not allowed to leave the variable argument out
1080 entirely; but you are allowed to pass an empty argument.  For example,
1081 this invocation is invalid in ISO C, because there is no comma after
1082 the string:
1084 @example
1085 debug ("A message")
1086 @end example
1088 GNU CPP permits you to completely omit the variable arguments in this
1089 way.  In the above examples, the compiler would complain, though since
1090 the expansion of the macro still has the extra comma after the format
1091 string.
1093 To help solve this problem, CPP behaves specially for variable arguments
1094 used with the token paste operator, @samp{##}.  If instead you write
1096 @example
1097 #define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
1098 @end example
1100 and if the variable arguments are omitted or empty, the @samp{##}
1101 operator causes the preprocessor to remove the comma before it.  If you
1102 do provide some variable arguments in your macro invocation, GNU CPP
1103 does not complain about the paste operation and instead places the
1104 variable arguments after the comma.  Just like any other pasted macro
1105 argument, these arguments are not macro expanded.
1107 @node Escaped Newlines
1108 @section Slightly Looser Rules for Escaped Newlines
1109 @cindex escaped newlines
1110 @cindex newlines (escaped)
1112 Recently, the non-traditional preprocessor has relaxed its treatment of
1113 escaped newlines.  Previously, the newline had to immediately follow a
1114 backslash.  The current implementation allows whitespace in the form of
1115 spaces, horizontal and vertical tabs, and form feeds between the
1116 backslash and the subsequent newline.  The preprocessor issues a
1117 warning, but treats it as a valid escaped newline and combines the two
1118 lines to form a single logical line.  This works within comments and
1119 tokens, including multi-line strings, as well as between tokens.
1120 Comments are @emph{not} treated as whitespace for the purposes of this
1121 relaxation, since they have not yet been replaced with spaces.
1123 @node Multi-line Strings
1124 @section String Literals with Embedded Newlines
1125 @cindex multi-line string literals
1127 As an extension, GNU CPP permits string literals to cross multiple lines
1128 without escaping the embedded newlines.  Each embedded newline is
1129 replaced with a single @samp{\n} character in the resulting string
1130 literal, regardless of what form the newline took originally.
1132 CPP currently allows such strings in directives as well (other than the
1133 @samp{#include} family).  This is deprecated and will eventually be
1134 removed.
1136 @node Subscripting
1137 @section Non-Lvalue Arrays May Have Subscripts
1138 @cindex subscripting
1139 @cindex arrays, non-lvalue
1141 @cindex subscripting and function values
1142 Subscripting is allowed on arrays that are not lvalues, even though the
1143 unary @samp{&} operator is not.  For example, this is valid in GNU C though
1144 not valid in other C dialects:
1146 @example
1147 @group
1148 struct foo @{int a[4];@};
1150 struct foo f();
1152 bar (int index)
1154   return f().a[index];
1156 @end group
1157 @end example
1159 @node Pointer Arith
1160 @section Arithmetic on @code{void}- and Function-Pointers
1161 @cindex void pointers, arithmetic
1162 @cindex void, size of pointer to
1163 @cindex function pointers, arithmetic
1164 @cindex function, size of pointer to
1166 In GNU C, addition and subtraction operations are supported on pointers to
1167 @code{void} and on pointers to functions.  This is done by treating the
1168 size of a @code{void} or of a function as 1.
1170 A consequence of this is that @code{sizeof} is also allowed on @code{void}
1171 and on function types, and returns 1.
1173 The option @samp{-Wpointer-arith} requests a warning if these extensions
1174 are used.
1176 @node Initializers
1177 @section Non-Constant Initializers
1178 @cindex initializers, non-constant
1179 @cindex non-constant initializers
1181 As in standard C++, the elements of an aggregate initializer for an
1182 automatic variable are not required to be constant expressions in GNU C.
1183 Here is an example of an initializer with run-time varying elements:
1185 @example
1186 foo (float f, float g)
1188   float beat_freqs[2] = @{ f-g, f+g @};
1189   @dots{}
1191 @end example
1193 @node Constructors
1194 @section Constructor Expressions
1195 @cindex constructor expressions
1196 @cindex initializations in expressions
1197 @cindex structures, constructor expression
1198 @cindex expressions, constructor
1200 GNU C supports constructor expressions.  A constructor looks like
1201 a cast containing an initializer.  Its value is an object of the
1202 type specified in the cast, containing the elements specified in
1203 the initializer.
1205 Usually, the specified type is a structure.  Assume that
1206 @code{struct foo} and @code{structure} are declared as shown:
1208 @example
1209 struct foo @{int a; char b[2];@} structure;
1210 @end example
1212 @noindent
1213 Here is an example of constructing a @code{struct foo} with a constructor:
1215 @example
1216 structure = ((struct foo) @{x + y, 'a', 0@});
1217 @end example
1219 @noindent
1220 This is equivalent to writing the following:
1222 @example
1224   struct foo temp = @{x + y, 'a', 0@};
1225   structure = temp;
1227 @end example
1229 You can also construct an array.  If all the elements of the constructor
1230 are (made up of) simple constant expressions, suitable for use in
1231 initializers, then the constructor is an lvalue and can be coerced to a
1232 pointer to its first element, as shown here:
1234 @example
1235 char **foo = (char *[]) @{ "x", "y", "z" @};
1236 @end example
1238 Array constructors whose elements are not simple constants are
1239 not very useful, because the constructor is not an lvalue.  There
1240 are only two valid ways to use it: to subscript it, or initialize
1241 an array variable with it.  The former is probably slower than a
1242 @code{switch} statement, while the latter does the same thing an
1243 ordinary C initializer would do.  Here is an example of
1244 subscripting an array constructor:
1246 @example
1247 output = ((int[]) @{ 2, x, 28 @}) [input];
1248 @end example
1250 Constructor expressions for scalar types and union types are is
1251 also allowed, but then the constructor expression is equivalent
1252 to a cast.
1254 @node Labeled Elements
1255 @section Labeled Elements in Initializers
1256 @cindex initializers with labeled elements
1257 @cindex labeled elements in initializers
1258 @cindex case labels in initializers
1260 Standard C89 requires the elements of an initializer to appear in a fixed
1261 order, the same as the order of the elements in the array or structure
1262 being initialized.
1264 In ISO C99 you can give the elements in any order, specifying the array
1265 indices or structure field names they apply to, and GNU C allows this as
1266 an extension in C89 mode as well.  This extension is not
1267 implemented in GNU C++.
1269 To specify an array index, write
1270 @samp{[@var{index}] =} before the element value.  For example,
1272 @example
1273 int a[6] = @{ [4] = 29, [2] = 15 @};
1274 @end example
1276 @noindent
1277 is equivalent to
1279 @example
1280 int a[6] = @{ 0, 0, 15, 0, 29, 0 @};
1281 @end example
1283 @noindent
1284 The index values must be constant expressions, even if the array being
1285 initialized is automatic.
1287 An alternative syntax for this which has been obsolete since GCC 2.5 but
1288 GCC still accepts is to write @samp{[@var{index}]} before the element
1289 value, with no @samp{=}.
1291 To initialize a range of elements to the same value, write
1292 @samp{[@var{first} ... @var{last}] = @var{value}}.  This is a GNU
1293 extension.  For example,
1295 @example
1296 int widths[] = @{ [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 @};
1297 @end example
1299 @noindent
1300 If the value in it has side-effects, the side-effects will happen only once,
1301 not for each initialized field by the range initializer.
1303 @noindent
1304 Note that the length of the array is the highest value specified
1305 plus one.
1307 In a structure initializer, specify the name of a field to initialize
1308 with @samp{.@var{fieldname} =} before the element value.  For example,
1309 given the following structure,
1311 @example
1312 struct point @{ int x, y; @};
1313 @end example
1315 @noindent
1316 the following initialization
1318 @example
1319 struct point p = @{ .y = yvalue, .x = xvalue @};
1320 @end example
1322 @noindent
1323 is equivalent to
1325 @example
1326 struct point p = @{ xvalue, yvalue @};
1327 @end example
1329 Another syntax which has the same meaning, obsolete since GCC 2.5, is
1330 @samp{@var{fieldname}:}, as shown here:
1332 @example
1333 struct point p = @{ y: yvalue, x: xvalue @};
1334 @end example
1336 You can also use an element label (with either the colon syntax or the
1337 period-equal syntax) when initializing a union, to specify which element
1338 of the union should be used.  For example,
1340 @example
1341 union foo @{ int i; double d; @};
1343 union foo f = @{ .d = 4 @};
1344 @end example
1346 @noindent
1347 will convert 4 to a @code{double} to store it in the union using
1348 the second element.  By contrast, casting 4 to type @code{union foo}
1349 would store it into the union as the integer @code{i}, since it is
1350 an integer.  (@xref{Cast to Union}.)
1352 You can combine this technique of naming elements with ordinary C
1353 initialization of successive elements.  Each initializer element that
1354 does not have a label applies to the next consecutive element of the
1355 array or structure.  For example,
1357 @example
1358 int a[6] = @{ [1] = v1, v2, [4] = v4 @};
1359 @end example
1361 @noindent
1362 is equivalent to
1364 @example
1365 int a[6] = @{ 0, v1, v2, 0, v4, 0 @};
1366 @end example
1368 Labeling the elements of an array initializer is especially useful
1369 when the indices are characters or belong to an @code{enum} type.
1370 For example:
1372 @example
1373 int whitespace[256]
1374   = @{ [' '] = 1, ['\t'] = 1, ['\h'] = 1,
1375       ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 @};
1376 @end example
1378 You can also write a series of @samp{.@var{fieldname}} and
1379 @samp{[@var{index}]} element labels before an @samp{=} to specify a
1380 nested subobject to initialize; the list is taken relative to the
1381 subobject corresponding to the closest surrounding brace pair.  For
1382 example, with the @samp{struct point} declaration above:
1384 @example
1385 struct point ptarray[10] = @{ [2].y = yv2, [2].x = xv2, [0].x = xv0 @};
1386 @end example
1388 @noindent
1389 If the same field is initialized multiple times, it will have value from
1390 the last initialization.  If any such overridden initialization has
1391 side-effect, it is unspecified whether the side-effect happens or not.
1392 Currently, gcc will discard them and issue a warning.
1394 @node Case Ranges
1395 @section Case Ranges
1396 @cindex case ranges
1397 @cindex ranges in case statements
1399 You can specify a range of consecutive values in a single @code{case} label,
1400 like this:
1402 @example
1403 case @var{low} ... @var{high}:
1404 @end example
1406 @noindent
1407 This has the same effect as the proper number of individual @code{case}
1408 labels, one for each integer value from @var{low} to @var{high}, inclusive.
1410 This feature is especially useful for ranges of ASCII character codes:
1412 @example
1413 case 'A' ... 'Z':
1414 @end example
1416 @strong{Be careful:} Write spaces around the @code{...}, for otherwise
1417 it may be parsed wrong when you use it with integer values.  For example,
1418 write this:
1420 @example
1421 case 1 ... 5:
1422 @end example
1424 @noindent
1425 rather than this:
1427 @example
1428 case 1...5:
1429 @end example
1431 @node Cast to Union
1432 @section Cast to a Union Type
1433 @cindex cast to a union
1434 @cindex union, casting to a
1436 A cast to union type is similar to other casts, except that the type
1437 specified is a union type.  You can specify the type either with
1438 @code{union @var{tag}} or with a typedef name.  A cast to union is actually
1439 a constructor though, not a cast, and hence does not yield an lvalue like
1440 normal casts.  (@xref{Constructors}.)
1442 The types that may be cast to the union type are those of the members
1443 of the union.  Thus, given the following union and variables:
1445 @example
1446 union foo @{ int i; double d; @};
1447 int x;
1448 double y;
1449 @end example
1451 @noindent
1452 both @code{x} and @code{y} can be cast to type @code{union} foo.
1454 Using the cast as the right-hand side of an assignment to a variable of
1455 union type is equivalent to storing in a member of the union:
1457 @example
1458 union foo u;
1459 @dots{}
1460 u = (union foo) x  @equiv{}  u.i = x
1461 u = (union foo) y  @equiv{}  u.d = y
1462 @end example
1464 You can also use the union cast as a function argument:
1466 @example
1467 void hack (union foo);
1468 @dots{}
1469 hack ((union foo) x);
1470 @end example
1472 @node Function Attributes
1473 @section Declaring Attributes of Functions
1474 @cindex function attributes
1475 @cindex declaring attributes of functions
1476 @cindex functions that never return
1477 @cindex functions that have no side effects
1478 @cindex functions in arbitrary sections
1479 @cindex functions that behave like malloc
1480 @cindex @code{volatile} applied to function
1481 @cindex @code{const} applied to function
1482 @cindex functions with @code{printf}, @code{scanf}, @code{strftime} or @code{strfmon} style arguments
1483 @cindex functions that are passed arguments in registers on the 386
1484 @cindex functions that pop the argument stack on the 386
1485 @cindex functions that do not pop the argument stack on the 386
1487 In GNU C, you declare certain things about functions called in your program
1488 which help the compiler optimize function calls and check your code more
1489 carefully.
1491 The keyword @code{__attribute__} allows you to specify special
1492 attributes when making a declaration.  This keyword is followed by an
1493 attribute specification inside double parentheses.  Fourteen attributes,
1494 @code{noreturn}, @code{pure}, @code{const}, @code{format},
1495 @code{format_arg}, @code{no_instrument_function}, @code{section},
1496 @code{constructor}, @code{destructor}, @code{unused}, @code{weak},
1497 @code{malloc}, @code{alias} and @code{no_check_memory_usage} are
1498 currently defined for functions.  Several other attributes are defined
1499 for functions on particular target systems.  Other attributes, including
1500 @code{section} are supported for variables declarations (@pxref{Variable
1501 Attributes}) and for types (@pxref{Type Attributes}).
1503 You may also specify attributes with @samp{__} preceding and following
1504 each keyword.  This allows you to use them in header files without
1505 being concerned about a possible macro of the same name.  For example,
1506 you may use @code{__noreturn__} instead of @code{noreturn}.
1508 @table @code
1509 @cindex @code{noreturn} function attribute
1510 @item noreturn
1511 A few standard library functions, such as @code{abort} and @code{exit},
1512 cannot return.  GNU CC knows this automatically.  Some programs define
1513 their own functions that never return.  You can declare them
1514 @code{noreturn} to tell the compiler this fact.  For example,
1516 @smallexample
1517 void fatal () __attribute__ ((noreturn));
1519 void
1520 fatal (@dots{})
1522   @dots{} /* @r{Print error message.} */ @dots{}
1523   exit (1);
1525 @end smallexample
1527 The @code{noreturn} keyword tells the compiler to assume that
1528 @code{fatal} cannot return.  It can then optimize without regard to what
1529 would happen if @code{fatal} ever did return.  This makes slightly
1530 better code.  More importantly, it helps avoid spurious warnings of
1531 uninitialized variables.
1533 Do not assume that registers saved by the calling function are
1534 restored before calling the @code{noreturn} function.
1536 It does not make sense for a @code{noreturn} function to have a return
1537 type other than @code{void}.
1539 The attribute @code{noreturn} is not implemented in GNU C versions
1540 earlier than 2.5.  An alternative way to declare that a function does
1541 not return, which works in the current version and in some older
1542 versions, is as follows:
1544 @smallexample
1545 typedef void voidfn ();
1547 volatile voidfn fatal;
1548 @end smallexample
1550 @cindex @code{pure} function attribute
1551 @item pure
1552 Many functions have no effects except the return value and their
1553 return value depends only on the parameters and/or global variables.
1554 Such a function can be subject
1555 to common subexpression elimination and loop optimization just as an
1556 arithmetic operator would be.  These functions should be declared
1557 with the attribute @code{pure}.  For example,
1559 @smallexample
1560 int square (int) __attribute__ ((pure));
1561 @end smallexample
1563 @noindent
1564 says that the hypothetical function @code{square} is safe to call
1565 fewer times than the program says.
1567 Some of common examples of pure functions are @code{strlen} or @code{memcmp}.
1568 Interesting non-pure functions are functions with infinite loops or those
1569 depending on volatile memory or other system resource, that may change between
1570 two consecutive calls (such as @code{feof} in a multithreading environment).
1572 The attribute @code{pure} is not implemented in GNU C versions earlier
1573 than 2.96.
1574 @cindex @code{const} function attribute
1575 @item const
1576 Many functions do not examine any values except their arguments, and
1577 have no effects except the return value.  Basically this is just slightly
1578 more strict class than the "pure" attribute above, since function is not
1579 allowed to read global memory.
1581 @cindex pointer arguments
1582 Note that a function that has pointer arguments and examines the data
1583 pointed to must @emph{not} be declared @code{const}.  Likewise, a
1584 function that calls a non-@code{const} function usually must not be
1585 @code{const}.  It does not make sense for a @code{const} function to
1586 return @code{void}.
1588 The attribute @code{const} is not implemented in GNU C versions earlier
1589 than 2.5.  An alternative way to declare that a function has no side
1590 effects, which works in the current version and in some older versions,
1591 is as follows:
1593 @smallexample
1594 typedef int intfn ();
1596 extern const intfn square;
1597 @end smallexample
1599 This approach does not work in GNU C++ from 2.6.0 on, since the language
1600 specifies that the @samp{const} must be attached to the return value.
1603 @item format (@var{archetype}, @var{string-index}, @var{first-to-check})
1604 @cindex @code{format} function attribute
1605 The @code{format} attribute specifies that a function takes @code{printf},
1606 @code{scanf}, @code{strftime} or @code{strfmon} style arguments which
1607 should be type-checked against a format string.  For example, the
1608 declaration:
1610 @smallexample
1611 extern int
1612 my_printf (void *my_object, const char *my_format, ...)
1613       __attribute__ ((format (printf, 2, 3)));
1614 @end smallexample
1616 @noindent
1617 causes the compiler to check the arguments in calls to @code{my_printf}
1618 for consistency with the @code{printf} style format string argument
1619 @code{my_format}.
1621 The parameter @var{archetype} determines how the format string is
1622 interpreted, and should be @code{printf}, @code{scanf}, @code{strftime}
1623 or @code{strfmon}.  (You can also use @code{__printf__},
1624 @code{__scanf__}, @code{__strftime__} or @code{__strfmon__}.)  The
1625 parameter @var{string-index} specifies which argument is the format
1626 string argument (starting from 1), while @var{first-to-check} is the
1627 number of the first argument to check against the format string.  For
1628 functions where the arguments are not available to be checked (such as
1629 @code{vprintf}), specify the third parameter as zero.  In this case the
1630 compiler only checks the format string for consistency.  For
1631 @code{strftime} formats, the third parameter is required to be zero.
1633 In the example above, the format string (@code{my_format}) is the second
1634 argument of the function @code{my_print}, and the arguments to check
1635 start with the third argument, so the correct parameters for the format
1636 attribute are 2 and 3.
1638 The @code{format} attribute allows you to identify your own functions
1639 which take format strings as arguments, so that GNU CC can check the
1640 calls to these functions for errors.  The compiler always (unless
1641 @samp{-ffreestanding} is used) checks formats
1642 for the standard library functions @code{printf}, @code{fprintf},
1643 @code{sprintf}, @code{scanf}, @code{fscanf}, @code{sscanf}, @code{strftime},
1644 @code{vprintf}, @code{vfprintf} and @code{vsprintf} whenever such
1645 warnings are requested (using @samp{-Wformat}), so there is no need to
1646 modify the header file @file{stdio.h}.  In C99 mode, the functions
1647 @code{snprintf}, @code{vsnprintf}, @code{vscanf}, @code{vfscanf} and
1648 @code{vsscanf} are also checked.  Except in strictly conforming C
1649 standard modes, the X/Open function @code{strfmon} is also checked.
1650 @xref{C Dialect Options,,Options Controlling C Dialect}.
1652 @item format_arg (@var{string-index})
1653 @cindex @code{format_arg} function attribute
1654 The @code{format_arg} attribute specifies that a function takes a format
1655 string for a @code{printf}, @code{scanf}, @code{strftime} or
1656 @code{strfmon} style function and modifies it (for example, to translate
1657 it into another language), so the result can be passed to a
1658 @code{printf}, @code{scanf}, @code{strftime} or @code{strfmon} style
1659 function (with the remaining arguments to the format function the same
1660 as they would have been for the unmodified string).  For example, the
1661 declaration:
1663 @smallexample
1664 extern char *
1665 my_dgettext (char *my_domain, const char *my_format)
1666       __attribute__ ((format_arg (2)));
1667 @end smallexample
1669 @noindent
1670 causes the compiler to check the arguments in calls to a @code{printf},
1671 @code{scanf}, @code{strftime} or @code{strfmon} type function, whose
1672 format string argument is a call to the @code{my_dgettext} function, for
1673 consistency with the format string argument @code{my_format}.  If the
1674 @code{format_arg} attribute had not been specified, all the compiler
1675 could tell in such calls to format functions would be that the format
1676 string argument is not constant; this would generate a warning when
1677 @code{-Wformat-nonliteral} is used, but the calls could not be checked
1678 without the attribute.
1680 The parameter @var{string-index} specifies which argument is the format
1681 string argument (starting from 1).
1683 The @code{format-arg} attribute allows you to identify your own
1684 functions which modify format strings, so that GNU CC can check the
1685 calls to @code{printf}, @code{scanf}, @code{strftime} or @code{strfmon}
1686 type function whose operands are a call to one of your own function.
1687 The compiler always treats @code{gettext}, @code{dgettext}, and
1688 @code{dcgettext} in this manner except when strict ISO C support is
1689 requested by @samp{-ansi} or an appropriate @samp{-std} option, or
1690 @samp{-ffreestanding} is used.  @xref{C Dialect Options,,Options
1691 Controlling C Dialect}.
1693 @item no_instrument_function
1694 @cindex @code{no_instrument_function} function attribute
1695 If @samp{-finstrument-functions} is given, profiling function calls will
1696 be generated at entry and exit of most user-compiled functions.
1697 Functions with this attribute will not be so instrumented.
1699 @item section ("section-name")
1700 @cindex @code{section} function attribute
1701 Normally, the compiler places the code it generates in the @code{text} section.
1702 Sometimes, however, you need additional sections, or you need certain
1703 particular functions to appear in special sections.  The @code{section}
1704 attribute specifies that a function lives in a particular section.
1705 For example, the declaration:
1707 @smallexample
1708 extern void foobar (void) __attribute__ ((section ("bar")));
1709 @end smallexample
1711 @noindent
1712 puts the function @code{foobar} in the @code{bar} section.
1714 Some file formats do not support arbitrary sections so the @code{section}
1715 attribute is not available on all platforms.
1716 If you need to map the entire contents of a module to a particular
1717 section, consider using the facilities of the linker instead.
1719 @item constructor
1720 @itemx destructor
1721 @cindex @code{constructor} function attribute
1722 @cindex @code{destructor} function attribute
1723 The @code{constructor} attribute causes the function to be called
1724 automatically before execution enters @code{main ()}.  Similarly, the
1725 @code{destructor} attribute causes the function to be called
1726 automatically after @code{main ()} has completed or @code{exit ()} has
1727 been called.  Functions with these attributes are useful for
1728 initializing data that will be used implicitly during the execution of
1729 the program.
1731 These attributes are not currently implemented for Objective C.
1733 @item unused
1734 This attribute, attached to a function, means that the function is meant
1735 to be possibly unused.  GNU CC will not produce a warning for this
1736 function.  GNU C++ does not currently support this attribute as
1737 definitions without parameters are valid in C++.
1739 @item weak
1740 @cindex @code{weak} attribute
1741 The @code{weak} attribute causes the declaration to be emitted as a weak
1742 symbol rather than a global.  This is primarily useful in defining
1743 library functions which can be overridden in user code, though it can
1744 also be used with non-function declarations.  Weak symbols are supported
1745 for ELF targets, and also for a.out targets when using the GNU assembler
1746 and linker.
1748 @item malloc
1749 @cindex @code{malloc} attribute
1750 The @code{malloc} attribute is used to tell the compiler that a function
1751 may be treated as if it were the malloc function.  The compiler assumes
1752 that calls to malloc result in a pointers that cannot alias anything.
1753 This will often improve optimization.
1755 @item alias ("target")
1756 @cindex @code{alias} attribute
1757 The @code{alias} attribute causes the declaration to be emitted as an
1758 alias for another symbol, which must be specified.  For instance,
1760 @smallexample
1761 void __f () @{ /* do something */; @}
1762 void f () __attribute__ ((weak, alias ("__f")));
1763 @end smallexample
1765 declares @samp{f} to be a weak alias for @samp{__f}.  In C++, the
1766 mangled name for the target must be used.
1768 Not all target machines support this attribute.
1770 @item no_check_memory_usage
1771 @cindex @code{no_check_memory_usage} function attribute
1772 The @code{no_check_memory_usage} attribute causes GNU CC to omit checks
1773 of memory references when it generates code for that function.  Normally
1774 if you specify @samp{-fcheck-memory-usage} (see @pxref{Code Gen
1775 Options}), GNU CC generates calls to support routines before most memory
1776 accesses to permit support code to record usage and detect uses of
1777 uninitialized or unallocated storage.  Since GNU CC cannot handle
1778 @code{asm} statements properly they are not allowed in such functions.
1779 If you declare a function with this attribute, GNU CC will not generate
1780 memory checking code for that function, permitting the use of @code{asm}
1781 statements without having to compile that function with different
1782 options.  This also allows you to write support routines of your own if
1783 you wish, without getting infinite recursion if they get compiled with
1784 @code{-fcheck-memory-usage}.
1786 @item regparm (@var{number})
1787 @cindex functions that are passed arguments in registers on the 386
1788 On the Intel 386, the @code{regparm} attribute causes the compiler to
1789 pass up to @var{number} integer arguments in registers @var{EAX},
1790 @var{EDX}, and @var{ECX} instead of on the stack.  Functions that take a
1791 variable number of arguments will continue to be passed all of their
1792 arguments on the stack.
1794 @item stdcall
1795 @cindex functions that pop the argument stack on the 386
1796 On the Intel 386, the @code{stdcall} attribute causes the compiler to
1797 assume that the called function will pop off the stack space used to
1798 pass arguments, unless it takes a variable number of arguments.
1800 The PowerPC compiler for Windows NT currently ignores the @code{stdcall}
1801 attribute.
1803 @item cdecl
1804 @cindex functions that do pop the argument stack on the 386
1805 On the Intel 386, the @code{cdecl} attribute causes the compiler to
1806 assume that the calling function will pop off the stack space used to
1807 pass arguments.  This is
1808 useful to override the effects of the @samp{-mrtd} switch.
1810 The PowerPC compiler for Windows NT currently ignores the @code{cdecl}
1811 attribute.
1813 @item longcall
1814 @cindex functions called via pointer on the RS/6000 and PowerPC
1815 On the RS/6000 and PowerPC, the @code{longcall} attribute causes the
1816 compiler to always call the function via a pointer, so that functions
1817 which reside further than 64 megabytes (67,108,864 bytes) from the
1818 current location can be called.
1820 @item long_call/short_call
1821 @cindex indirect calls on ARM
1822 This attribute allows to specify how to call a particular function on
1823 ARM.  Both attributes override the @code{-mlong-calls} (@pxref{ARM Options})
1824 command line switch and @code{#pragma long_calls} settings.  The
1825 @code{long_call} attribute causes the compiler to always call the
1826 function by first loading its address into a register and then using the
1827 contents of that register.   The @code{short_call} attribute always places
1828 the offset to the function from the call site into the @samp{BL}
1829 instruction directly.
1831 @item dllimport
1832 @cindex functions which are imported from a dll on PowerPC Windows NT
1833 On the PowerPC running Windows NT, the @code{dllimport} attribute causes
1834 the compiler to call the function via a global pointer to the function
1835 pointer that is set up by the Windows NT dll library.  The pointer name
1836 is formed by combining @code{__imp_} and the function name.
1838 @item dllexport
1839 @cindex functions which are exported from a dll on PowerPC Windows NT
1840 On the PowerPC running Windows NT, the @code{dllexport} attribute causes
1841 the compiler to provide a global pointer to the function pointer, so
1842 that it can be called with the @code{dllimport} attribute.  The pointer
1843 name is formed by combining @code{__imp_} and the function name.
1845 @item exception (@var{except-func} [, @var{except-arg}])
1846 @cindex functions which specify exception handling on PowerPC Windows NT
1847 On the PowerPC running Windows NT, the @code{exception} attribute causes
1848 the compiler to modify the structured exception table entry it emits for
1849 the declared function.  The string or identifier @var{except-func} is
1850 placed in the third entry of the structured exception table.  It
1851 represents a function, which is called by the exception handling
1852 mechanism if an exception occurs.  If it was specified, the string or
1853 identifier @var{except-arg} is placed in the fourth entry of the
1854 structured exception table.
1856 @item function_vector
1857 @cindex calling functions through the function vector on the H8/300 processors
1858 Use this option on the H8/300 and H8/300H to indicate that the specified
1859 function should be called through the function vector.  Calling a
1860 function through the function vector will reduce code size, however;
1861 the function vector has a limited size (maximum 128 entries on the H8/300
1862 and 64 entries on the H8/300H) and shares space with the interrupt vector.
1864 You must use GAS and GLD from GNU binutils version 2.7 or later for
1865 this option to work correctly.
1867 @item interrupt_handler
1868 @cindex interrupt handler functions on the H8/300 processors
1869 Use this option on the H8/300 and H8/300H to indicate that the specified
1870 function is an interrupt handler.  The compiler will generate function
1871 entry and exit sequences suitable for use in an interrupt handler when this
1872 attribute is present.
1874 @item interrupt
1875 @cindex interrupt handler functions
1876 Use this option on the ARM, AVR and M32R/D ports to indicate that the
1877 specified function is an interrupt handler.  The compiler will generate
1878 function entry and exit sequences suitable for use in an interrupt
1879 handler when this attribute is present.
1881 Note, interrupt handlers for the H8/300 and H8/300H processors can be
1882 specified via the @code{interrupt_handler} attribute.
1884 Note, on the AVR interrupts will be enabled inside the function.
1886 Note, for the ARM you can specify the kind of interrupt to be handled by
1887 adding an optional parameter to the interrupt attribute like this:
1889 @smallexample
1890 void f () __attribute__ ((interrupt ("IRQ")));
1891 @end smallexample
1893 Permissible values for this parameter are: IRQ, FIQ, SWI, ABORT and UNDEF.
1895 @item eightbit_data
1896 @cindex eight bit data on the H8/300 and H8/300H
1897 Use this option on the H8/300 and H8/300H to indicate that the specified
1898 variable should be placed into the eight bit data section.
1899 The compiler will generate more efficient code for certain operations
1900 on data in the eight bit data area.  Note the eight bit data area is limited to
1901 256 bytes of data.
1903 You must use GAS and GLD from GNU binutils version 2.7 or later for
1904 this option to work correctly.
1906 @item tiny_data
1907 @cindex tiny data section on the H8/300H
1908 Use this option on the H8/300H to indicate that the specified
1909 variable should be placed into the tiny data section.
1910 The compiler will generate more efficient code for loads and stores
1911 on data in the tiny data section.  Note the tiny data area is limited to
1912 slightly under 32kbytes of data.
1914 @item signal
1915 @cindex signal handler functions on the AVR processors
1916 Use this option on the AVR to indicate that the specified
1917 function is an signal handler.  The compiler will generate function
1918 entry and exit sequences suitable for use in an signal handler when this
1919 attribute is present. Interrupts will be disabled inside function.
1921 @item naked
1922 @cindex function without a prologue/epilogue code
1923 Use this option on the ARM or AVR ports to indicate that the specified
1924 function do not need prologue/epilogue sequences generated by the
1925 compiler.  It is up to the programmer to provide these sequences.
1927 @item model (@var{model-name})
1928 @cindex function addressability on the M32R/D
1929 Use this attribute on the M32R/D to set the addressability of an object,
1930 and the code generated for a function.
1931 The identifier @var{model-name} is one of @code{small}, @code{medium},
1932 or @code{large}, representing each of the code models.
1934 Small model objects live in the lower 16MB of memory (so that their
1935 addresses can be loaded with the @code{ld24} instruction), and are
1936 callable with the @code{bl} instruction.
1938 Medium model objects may live anywhere in the 32 bit address space (the
1939 compiler will generate @code{seth/add3} instructions to load their addresses),
1940 and are callable with the @code{bl} instruction.
1942 Large model objects may live anywhere in the 32 bit address space (the
1943 compiler will generate @code{seth/add3} instructions to load their addresses),
1944 and may not be reachable with the @code{bl} instruction (the compiler will
1945 generate the much slower @code{seth/add3/jl} instruction sequence).
1947 @end table
1949 You can specify multiple attributes in a declaration by separating them
1950 by commas within the double parentheses or by immediately following an
1951 attribute declaration with another attribute declaration.
1953 @cindex @code{#pragma}, reason for not using
1954 @cindex pragma, reason for not using
1955 Some people object to the @code{__attribute__} feature, suggesting that
1956 ISO C's @code{#pragma} should be used instead.  At the time
1957 @code{__attribute__} was designed, there were two reasons for not doing
1958 this.
1960 @enumerate
1961 @item
1962 It is impossible to generate @code{#pragma} commands from a macro.
1964 @item
1965 There is no telling what the same @code{#pragma} might mean in another
1966 compiler.
1967 @end enumerate
1969 These two reasons applied to almost any application that might have been
1970 proposed for @code{#pragma}.  It was basically a mistake to use
1971 @code{#pragma} for @emph{anything}.
1973 The ISO C99 standard includes @code{_Pragma}, which now allows pragmas
1974 to be generated from macros.  In addition, a @code{#pragma GCC}
1975 namespace is now in use for GCC-specific pragmas.  However, it has been
1976 found convenient to use @code{__attribute__} to achieve a natural
1977 attachment of attributes to their corresponding declarations, whereas
1978 @code{#pragma GCC} is of use for constructs that do not naturally form
1979 part of the grammar.  @xref{Other Directives,,Miscellaneous
1980 Preprocessing Directives, cpp, The C Preprocessor}.
1982 @node Function Prototypes
1983 @section Prototypes and Old-Style Function Definitions
1984 @cindex function prototype declarations
1985 @cindex old-style function definitions
1986 @cindex promotion of formal parameters
1988 GNU C extends ISO C to allow a function prototype to override a later
1989 old-style non-prototype definition.  Consider the following example:
1991 @example
1992 /* @r{Use prototypes unless the compiler is old-fashioned.}  */
1993 #ifdef __STDC__
1994 #define P(x) x
1995 #else
1996 #define P(x) ()
1997 #endif
1999 /* @r{Prototype function declaration.}  */
2000 int isroot P((uid_t));
2002 /* @r{Old-style function definition.}  */
2004 isroot (x)   /* ??? lossage here ??? */
2005      uid_t x;
2007   return x == 0;
2009 @end example
2011 Suppose the type @code{uid_t} happens to be @code{short}.  ISO C does
2012 not allow this example, because subword arguments in old-style
2013 non-prototype definitions are promoted.  Therefore in this example the
2014 function definition's argument is really an @code{int}, which does not
2015 match the prototype argument type of @code{short}.
2017 This restriction of ISO C makes it hard to write code that is portable
2018 to traditional C compilers, because the programmer does not know
2019 whether the @code{uid_t} type is @code{short}, @code{int}, or
2020 @code{long}.  Therefore, in cases like these GNU C allows a prototype
2021 to override a later old-style definition.  More precisely, in GNU C, a
2022 function prototype argument type overrides the argument type specified
2023 by a later old-style definition if the former type is the same as the
2024 latter type before promotion.  Thus in GNU C the above example is
2025 equivalent to the following:
2027 @example
2028 int isroot (uid_t);
2031 isroot (uid_t x)
2033   return x == 0;
2035 @end example
2037 GNU C++ does not support old-style function definitions, so this
2038 extension is irrelevant.
2040 @node C++ Comments
2041 @section C++ Style Comments
2042 @cindex //
2043 @cindex C++ comments
2044 @cindex comments, C++ style
2046 In GNU C, you may use C++ style comments, which start with @samp{//} and
2047 continue until the end of the line.  Many other C implementations allow
2048 such comments, and they are likely to be in a future C standard.
2049 However, C++ style comments are not recognized if you specify
2050 @w{@samp{-ansi}}, a @option{-std} option specifying a version of ISO C
2051 before C99, or @w{@samp{-traditional}}, since they are incompatible
2052 with traditional constructs like @code{dividend//*comment*/divisor}.
2054 @node Dollar Signs
2055 @section Dollar Signs in Identifier Names
2056 @cindex $
2057 @cindex dollar signs in identifier names
2058 @cindex identifier names, dollar signs in
2060 In GNU C, you may normally use dollar signs in identifier names.
2061 This is because many traditional C implementations allow such identifiers.
2062 However, dollar signs in identifiers are not supported on a few target
2063 machines, typically because the target assembler does not allow them.
2065 @node Character Escapes
2066 @section The Character @key{ESC} in Constants
2068 You can use the sequence @samp{\e} in a string or character constant to
2069 stand for the ASCII character @key{ESC}.
2071 @node Alignment
2072 @section Inquiring on Alignment of Types or Variables
2073 @cindex alignment
2074 @cindex type alignment
2075 @cindex variable alignment
2077 The keyword @code{__alignof__} allows you to inquire about how an object
2078 is aligned, or the minimum alignment usually required by a type.  Its
2079 syntax is just like @code{sizeof}.
2081 For example, if the target machine requires a @code{double} value to be
2082 aligned on an 8-byte boundary, then @code{__alignof__ (double)} is 8.
2083 This is true on many RISC machines.  On more traditional machine
2084 designs, @code{__alignof__ (double)} is 4 or even 2.
2086 Some machines never actually require alignment; they allow reference to any
2087 data type even at an odd addresses.  For these machines, @code{__alignof__}
2088 reports the @emph{recommended} alignment of a type.
2090 When the operand of @code{__alignof__} is an lvalue rather than a type, the
2091 value is the largest alignment that the lvalue is known to have.  It may
2092 have this alignment as a result of its data type, or because it is part of
2093 a structure and inherits alignment from that structure.  For example, after
2094 this declaration:
2096 @example
2097 struct foo @{ int x; char y; @} foo1;
2098 @end example
2100 @noindent
2101 the value of @code{__alignof__ (foo1.y)} is probably 2 or 4, the same as
2102 @code{__alignof__ (int)}, even though the data type of @code{foo1.y}
2103 does not itself demand any alignment.@refill
2105 It is an error to ask for the alignment of an incomplete type.
2107 A related feature which lets you specify the alignment of an object is
2108 @code{__attribute__ ((aligned (@var{alignment})))}; see the following
2109 section.
2111 @node Variable Attributes
2112 @section Specifying Attributes of Variables
2113 @cindex attribute of variables
2114 @cindex variable attributes
2116 The keyword @code{__attribute__} allows you to specify special
2117 attributes of variables or structure fields.  This keyword is followed
2118 by an attribute specification inside double parentheses.  Eight
2119 attributes are currently defined for variables: @code{aligned},
2120 @code{mode}, @code{nocommon}, @code{packed}, @code{section},
2121 @code{transparent_union}, @code{unused}, and @code{weak}.  Some other
2122 attributes are defined for variables on particular target systems.  Other
2123 attributes are available for functions (@pxref{Function Attributes}) and
2124 for types (@pxref{Type Attributes}).  Other front-ends might define more
2125 attributes (@pxref{C++ Extensions,,Extensions to the C++ Language}).
2127 You may also specify attributes with @samp{__} preceding and following
2128 each keyword.  This allows you to use them in header files without
2129 being concerned about a possible macro of the same name.  For example,
2130 you may use @code{__aligned__} instead of @code{aligned}.
2132 @table @code
2133 @cindex @code{aligned} attribute
2134 @item aligned (@var{alignment})
2135 This attribute specifies a minimum alignment for the variable or
2136 structure field, measured in bytes.  For example, the declaration:
2138 @smallexample
2139 int x __attribute__ ((aligned (16))) = 0;
2140 @end smallexample
2142 @noindent
2143 causes the compiler to allocate the global variable @code{x} on a
2144 16-byte boundary.  On a 68040, this could be used in conjunction with
2145 an @code{asm} expression to access the @code{move16} instruction which
2146 requires 16-byte aligned operands.
2148 You can also specify the alignment of structure fields.  For example, to
2149 create a double-word aligned @code{int} pair, you could write:
2151 @smallexample
2152 struct foo @{ int x[2] __attribute__ ((aligned (8))); @};
2153 @end smallexample
2155 @noindent
2156 This is an alternative to creating a union with a @code{double} member
2157 that forces the union to be double-word aligned.
2159 It is not possible to specify the alignment of functions; the alignment
2160 of functions is determined by the machine's requirements and cannot be
2161 changed.  You cannot specify alignment for a typedef name because such a
2162 name is just an alias, not a distinct type.
2164 As in the preceding examples, you can explicitly specify the alignment
2165 (in bytes) that you wish the compiler to use for a given variable or
2166 structure field.  Alternatively, you can leave out the alignment factor
2167 and just ask the compiler to align a variable or field to the maximum
2168 useful alignment for the target machine you are compiling for.  For
2169 example, you could write:
2171 @smallexample
2172 short array[3] __attribute__ ((aligned));
2173 @end smallexample
2175 Whenever you leave out the alignment factor in an @code{aligned} attribute
2176 specification, the compiler automatically sets the alignment for the declared
2177 variable or field to the largest alignment which is ever used for any data
2178 type on the target machine you are compiling for.  Doing this can often make
2179 copy operations more efficient, because the compiler can use whatever
2180 instructions copy the biggest chunks of memory when performing copies to
2181 or from the variables or fields that you have aligned this way.
2183 The @code{aligned} attribute can only increase the alignment; but you
2184 can decrease it by specifying @code{packed} as well.  See below.
2186 Note that the effectiveness of @code{aligned} attributes may be limited
2187 by inherent limitations in your linker.  On many systems, the linker is
2188 only able to arrange for variables to be aligned up to a certain maximum
2189 alignment.  (For some linkers, the maximum supported alignment may
2190 be very very small.)  If your linker is only able to align variables
2191 up to a maximum of 8 byte alignment, then specifying @code{aligned(16)}
2192 in an @code{__attribute__} will still only provide you with 8 byte
2193 alignment.  See your linker documentation for further information.
2195 @item mode (@var{mode})
2196 @cindex @code{mode} attribute
2197 This attribute specifies the data type for the declaration---whichever
2198 type corresponds to the mode @var{mode}.  This in effect lets you
2199 request an integer or floating point type according to its width.
2201 You may also specify a mode of @samp{byte} or @samp{__byte__} to
2202 indicate the mode corresponding to a one-byte integer, @samp{word} or
2203 @samp{__word__} for the mode of a one-word integer, and @samp{pointer}
2204 or @samp{__pointer__} for the mode used to represent pointers.
2206 @item nocommon
2207 @cindex @code{nocommon} attribute
2208 This attribute specifies requests GNU CC not to place a variable
2209 ``common'' but instead to allocate space for it directly.  If you
2210 specify the @samp{-fno-common} flag, GNU CC will do this for all
2211 variables.
2213 Specifying the @code{nocommon} attribute for a variable provides an
2214 initialization of zeros.  A variable may only be initialized in one
2215 source file.
2217 @item packed
2218 @cindex @code{packed} attribute
2219 The @code{packed} attribute specifies that a variable or structure field
2220 should have the smallest possible alignment---one byte for a variable,
2221 and one bit for a field, unless you specify a larger value with the
2222 @code{aligned} attribute.
2224 Here is a structure in which the field @code{x} is packed, so that it
2225 immediately follows @code{a}:
2227 @example
2228 struct foo
2230   char a;
2231   int x[2] __attribute__ ((packed));
2233 @end example
2235 @item section ("section-name")
2236 @cindex @code{section} variable attribute
2237 Normally, the compiler places the objects it generates in sections like
2238 @code{data} and @code{bss}.  Sometimes, however, you need additional sections,
2239 or you need certain particular variables to appear in special sections,
2240 for example to map to special hardware.  The @code{section}
2241 attribute specifies that a variable (or function) lives in a particular
2242 section.  For example, this small program uses several specific section names:
2244 @smallexample
2245 struct duart a __attribute__ ((section ("DUART_A"))) = @{ 0 @};
2246 struct duart b __attribute__ ((section ("DUART_B"))) = @{ 0 @};
2247 char stack[10000] __attribute__ ((section ("STACK"))) = @{ 0 @};
2248 int init_data __attribute__ ((section ("INITDATA"))) = 0;
2250 main()
2252   /* Initialize stack pointer */
2253   init_sp (stack + sizeof (stack));
2255   /* Initialize initialized data */
2256   memcpy (&init_data, &data, &edata - &data);
2258   /* Turn on the serial ports */
2259   init_duart (&a);
2260   init_duart (&b);
2262 @end smallexample
2264 @noindent
2265 Use the @code{section} attribute with an @emph{initialized} definition
2266 of a @emph{global} variable, as shown in the example.  GNU CC issues
2267 a warning and otherwise ignores the @code{section} attribute in
2268 uninitialized variable declarations.
2270 You may only use the @code{section} attribute with a fully initialized
2271 global definition because of the way linkers work.  The linker requires
2272 each object be defined once, with the exception that uninitialized
2273 variables tentatively go in the @code{common} (or @code{bss}) section
2274 and can be multiply "defined".  You can force a variable to be
2275 initialized with the @samp{-fno-common} flag or the @code{nocommon}
2276 attribute.
2278 Some file formats do not support arbitrary sections so the @code{section}
2279 attribute is not available on all platforms.
2280 If you need to map the entire contents of a module to a particular
2281 section, consider using the facilities of the linker instead.
2283 @item shared
2284 @cindex @code{shared} variable attribute
2285 On Windows NT, in addition to putting variable definitions in a named 
2286 section, the section can also be shared among all running copies of an 
2287 executable or DLL. For example, this small program defines shared data 
2288 by putting it in a named section "shared" and marking the section 
2289 shareable:
2291 @smallexample
2292 int foo __attribute__((section ("shared"), shared)) = 0;
2295 main()
2297   /* Read and write foo. All running copies see the same value. */
2298   return 0;
2300 @end smallexample
2302 @noindent
2303 You may only use the @code{shared} attribute along with @code{section}
2304 attribute with a fully initialized global definition because of the way 
2305 linkers work.  See @code{section} attribute for more information.
2307 The @code{shared} attribute is only available on Windows NT.
2309 @item transparent_union
2310 This attribute, attached to a function parameter which is a union, means
2311 that the corresponding argument may have the type of any union member,
2312 but the argument is passed as if its type were that of the first union
2313 member.  For more details see @xref{Type Attributes}.  You can also use
2314 this attribute on a @code{typedef} for a union data type; then it
2315 applies to all function parameters with that type.
2317 @item unused
2318 This attribute, attached to a variable, means that the variable is meant
2319 to be possibly unused.  GNU CC will not produce a warning for this
2320 variable.
2322 @item weak
2323 The @code{weak} attribute is described in @xref{Function Attributes}.
2325 @item model (@var{model-name})
2326 @cindex variable addressability on the M32R/D
2327 Use this attribute on the M32R/D to set the addressability of an object.
2328 The identifier @var{model-name} is one of @code{small}, @code{medium},
2329 or @code{large}, representing each of the code models.
2331 Small model objects live in the lower 16MB of memory (so that their
2332 addresses can be loaded with the @code{ld24} instruction).
2334 Medium and large model objects may live anywhere in the 32 bit address space
2335 (the compiler will generate @code{seth/add3} instructions to load their
2336 addresses).
2338 @end table
2340 To specify multiple attributes, separate them by commas within the
2341 double parentheses: for example, @samp{__attribute__ ((aligned (16),
2342 packed))}.
2344 @node Type Attributes
2345 @section Specifying Attributes of Types
2346 @cindex attribute of types
2347 @cindex type attributes
2349 The keyword @code{__attribute__} allows you to specify special
2350 attributes of @code{struct} and @code{union} types when you define such
2351 types.  This keyword is followed by an attribute specification inside
2352 double parentheses.  Four attributes are currently defined for types:
2353 @code{aligned}, @code{packed}, @code{transparent_union}, and @code{unused}.
2354 Other attributes are defined for functions (@pxref{Function Attributes}) and
2355 for variables (@pxref{Variable Attributes}).
2357 You may also specify any one of these attributes with @samp{__}
2358 preceding and following its keyword.  This allows you to use these
2359 attributes in header files without being concerned about a possible
2360 macro of the same name.  For example, you may use @code{__aligned__}
2361 instead of @code{aligned}.
2363 You may specify the @code{aligned} and @code{transparent_union}
2364 attributes either in a @code{typedef} declaration or just past the
2365 closing curly brace of a complete enum, struct or union type
2366 @emph{definition} and the @code{packed} attribute only past the closing
2367 brace of a definition.
2369 You may also specify attributes between the enum, struct or union
2370 tag and the name of the type rather than after the closing brace.
2372 @table @code
2373 @cindex @code{aligned} attribute
2374 @item aligned (@var{alignment})
2375 This attribute specifies a minimum alignment (in bytes) for variables
2376 of the specified type.  For example, the declarations:
2378 @smallexample
2379 struct S @{ short f[3]; @} __attribute__ ((aligned (8)));
2380 typedef int more_aligned_int __attribute__ ((aligned (8)));
2381 @end smallexample
2383 @noindent
2384 force the compiler to insure (as far as it can) that each variable whose
2385 type is @code{struct S} or @code{more_aligned_int} will be allocated and
2386 aligned @emph{at least} on a 8-byte boundary.  On a Sparc, having all
2387 variables of type @code{struct S} aligned to 8-byte boundaries allows
2388 the compiler to use the @code{ldd} and @code{std} (doubleword load and
2389 store) instructions when copying one variable of type @code{struct S} to
2390 another, thus improving run-time efficiency.
2392 Note that the alignment of any given @code{struct} or @code{union} type
2393 is required by the ISO C standard to be at least a perfect multiple of
2394 the lowest common multiple of the alignments of all of the members of
2395 the @code{struct} or @code{union} in question.  This means that you @emph{can}
2396 effectively adjust the alignment of a @code{struct} or @code{union}
2397 type by attaching an @code{aligned} attribute to any one of the members
2398 of such a type, but the notation illustrated in the example above is a
2399 more obvious, intuitive, and readable way to request the compiler to
2400 adjust the alignment of an entire @code{struct} or @code{union} type.
2402 As in the preceding example, you can explicitly specify the alignment
2403 (in bytes) that you wish the compiler to use for a given @code{struct}
2404 or @code{union} type.  Alternatively, you can leave out the alignment factor
2405 and just ask the compiler to align a type to the maximum
2406 useful alignment for the target machine you are compiling for.  For
2407 example, you could write:
2409 @smallexample
2410 struct S @{ short f[3]; @} __attribute__ ((aligned));
2411 @end smallexample
2413 Whenever you leave out the alignment factor in an @code{aligned}
2414 attribute specification, the compiler automatically sets the alignment
2415 for the type to the largest alignment which is ever used for any data
2416 type on the target machine you are compiling for.  Doing this can often
2417 make copy operations more efficient, because the compiler can use
2418 whatever instructions copy the biggest chunks of memory when performing
2419 copies to or from the variables which have types that you have aligned
2420 this way.
2422 In the example above, if the size of each @code{short} is 2 bytes, then
2423 the size of the entire @code{struct S} type is 6 bytes.  The smallest
2424 power of two which is greater than or equal to that is 8, so the
2425 compiler sets the alignment for the entire @code{struct S} type to 8
2426 bytes.
2428 Note that although you can ask the compiler to select a time-efficient
2429 alignment for a given type and then declare only individual stand-alone
2430 objects of that type, the compiler's ability to select a time-efficient
2431 alignment is primarily useful only when you plan to create arrays of
2432 variables having the relevant (efficiently aligned) type.  If you
2433 declare or use arrays of variables of an efficiently-aligned type, then
2434 it is likely that your program will also be doing pointer arithmetic (or
2435 subscripting, which amounts to the same thing) on pointers to the
2436 relevant type, and the code that the compiler generates for these
2437 pointer arithmetic operations will often be more efficient for
2438 efficiently-aligned types than for other types.
2440 The @code{aligned} attribute can only increase the alignment; but you
2441 can decrease it by specifying @code{packed} as well.  See below.
2443 Note that the effectiveness of @code{aligned} attributes may be limited
2444 by inherent limitations in your linker.  On many systems, the linker is
2445 only able to arrange for variables to be aligned up to a certain maximum
2446 alignment.  (For some linkers, the maximum supported alignment may
2447 be very very small.)  If your linker is only able to align variables
2448 up to a maximum of 8 byte alignment, then specifying @code{aligned(16)}
2449 in an @code{__attribute__} will still only provide you with 8 byte
2450 alignment.  See your linker documentation for further information.
2452 @item packed
2453 This attribute, attached to an @code{enum}, @code{struct}, or
2454 @code{union} type definition, specified that the minimum required memory
2455 be used to represent the type.
2457 Specifying this attribute for @code{struct} and @code{union} types is
2458 equivalent to specifying the @code{packed} attribute on each of the
2459 structure or union members.  Specifying the @samp{-fshort-enums}
2460 flag on the line is equivalent to specifying the @code{packed}
2461 attribute on all @code{enum} definitions.
2463 You may only specify this attribute after a closing curly brace on an
2464 @code{enum} definition, not in a @code{typedef} declaration, unless that
2465 declaration also contains the definition of the @code{enum}.
2467 @item transparent_union
2468 This attribute, attached to a @code{union} type definition, indicates
2469 that any function parameter having that union type causes calls to that
2470 function to be treated in a special way.
2472 First, the argument corresponding to a transparent union type can be of
2473 any type in the union; no cast is required.  Also, if the union contains
2474 a pointer type, the corresponding argument can be a null pointer
2475 constant or a void pointer expression; and if the union contains a void
2476 pointer type, the corresponding argument can be any pointer expression.
2477 If the union member type is a pointer, qualifiers like @code{const} on
2478 the referenced type must be respected, just as with normal pointer
2479 conversions.
2481 Second, the argument is passed to the function using the calling
2482 conventions of first member of the transparent union, not the calling
2483 conventions of the union itself.  All members of the union must have the
2484 same machine representation; this is necessary for this argument passing
2485 to work properly.
2487 Transparent unions are designed for library functions that have multiple
2488 interfaces for compatibility reasons.  For example, suppose the
2489 @code{wait} function must accept either a value of type @code{int *} to
2490 comply with Posix, or a value of type @code{union wait *} to comply with
2491 the 4.1BSD interface.  If @code{wait}'s parameter were @code{void *},
2492 @code{wait} would accept both kinds of arguments, but it would also
2493 accept any other pointer type and this would make argument type checking
2494 less useful.  Instead, @code{<sys/wait.h>} might define the interface
2495 as follows:
2497 @smallexample
2498 typedef union
2499   @{
2500     int *__ip;
2501     union wait *__up;
2502   @} wait_status_ptr_t __attribute__ ((__transparent_union__));
2504 pid_t wait (wait_status_ptr_t);
2505 @end smallexample
2507 This interface allows either @code{int *} or @code{union wait *}
2508 arguments to be passed, using the @code{int *} calling convention.
2509 The program can call @code{wait} with arguments of either type:
2511 @example
2512 int w1 () @{ int w; return wait (&w); @}
2513 int w2 () @{ union wait w; return wait (&w); @}
2514 @end example
2516 With this interface, @code{wait}'s implementation might look like this:
2518 @example
2519 pid_t wait (wait_status_ptr_t p)
2521   return waitpid (-1, p.__ip, 0);
2523 @end example
2525 @item unused
2526 When attached to a type (including a @code{union} or a @code{struct}),
2527 this attribute means that variables of that type are meant to appear
2528 possibly unused.  GNU CC will not produce a warning for any variables of
2529 that type, even if the variable appears to do nothing.  This is often
2530 the case with lock or thread classes, which are usually defined and then
2531 not referenced, but contain constructors and destructors that have
2532 nontrivial bookkeeping functions.
2534 @end table
2536 To specify multiple attributes, separate them by commas within the
2537 double parentheses: for example, @samp{__attribute__ ((aligned (16),
2538 packed))}.
2540 @node Inline
2541 @section An Inline Function is As Fast As a Macro
2542 @cindex inline functions
2543 @cindex integrating function code
2544 @cindex open coding
2545 @cindex macros, inline alternative
2547 By declaring a function @code{inline}, you can direct GNU CC to
2548 integrate that function's code into the code for its callers.  This
2549 makes execution faster by eliminating the function-call overhead; in
2550 addition, if any of the actual argument values are constant, their known
2551 values may permit simplifications at compile time so that not all of the
2552 inline function's code needs to be included.  The effect on code size is
2553 less predictable; object code may be larger or smaller with function
2554 inlining, depending on the particular case.  Inlining of functions is an
2555 optimization and it really ``works'' only in optimizing compilation.  If
2556 you don't use @samp{-O}, no function is really inline.
2558 To declare a function inline, use the @code{inline} keyword in its
2559 declaration, like this:
2561 @example
2562 inline int
2563 inc (int *a)
2565   (*a)++;
2567 @end example
2569 (If you are writing a header file to be included in ISO C programs, write
2570 @code{__inline__} instead of @code{inline}.  @xref{Alternate Keywords}.)
2571 You can also make all ``simple enough'' functions inline with the option
2572 @samp{-finline-functions}. 
2574 Note that certain usages in a function definition can make it unsuitable
2575 for inline substitution.  Among these usages are: use of varargs, use of
2576 alloca, use of variable sized data types (@pxref{Variable Length}),
2577 use of computed goto (@pxref{Labels as Values}), use of nonlocal goto,
2578 and nested functions (@pxref{Nested Functions}).  Using @samp{-Winline}
2579 will warn when a function marked @code{inline} could not be substituted,
2580 and will give the reason for the failure.
2582 Note that in C and Objective C, unlike C++, the @code{inline} keyword
2583 does not affect the linkage of the function.
2585 @cindex automatic @code{inline} for C++ member fns
2586 @cindex @code{inline} automatic for C++ member fns
2587 @cindex member fns, automatically @code{inline}
2588 @cindex C++ member fns, automatically @code{inline}
2589 GNU CC automatically inlines member functions defined within the class
2590 body of C++ programs even if they are not explicitly declared
2591 @code{inline}.  (You can override this with @samp{-fno-default-inline};
2592 @pxref{C++ Dialect Options,,Options Controlling C++ Dialect}.)
2594 @cindex inline functions, omission of
2595 When a function is both inline and @code{static}, if all calls to the
2596 function are integrated into the caller, and the function's address is
2597 never used, then the function's own assembler code is never referenced.
2598 In this case, GNU CC does not actually output assembler code for the
2599 function, unless you specify the option @samp{-fkeep-inline-functions}.
2600 Some calls cannot be integrated for various reasons (in particular,
2601 calls that precede the function's definition cannot be integrated, and
2602 neither can recursive calls within the definition).  If there is a
2603 nonintegrated call, then the function is compiled to assembler code as
2604 usual.  The function must also be compiled as usual if the program
2605 refers to its address, because that can't be inlined.
2607 @cindex non-static inline function
2608 When an inline function is not @code{static}, then the compiler must assume
2609 that there may be calls from other source files; since a global symbol can
2610 be defined only once in any program, the function must not be defined in
2611 the other source files, so the calls therein cannot be integrated.
2612 Therefore, a non-@code{static} inline function is always compiled on its
2613 own in the usual fashion.
2615 If you specify both @code{inline} and @code{extern} in the function
2616 definition, then the definition is used only for inlining.  In no case
2617 is the function compiled on its own, not even if you refer to its
2618 address explicitly.  Such an address becomes an external reference, as
2619 if you had only declared the function, and had not defined it.
2621 This combination of @code{inline} and @code{extern} has almost the
2622 effect of a macro.  The way to use it is to put a function definition in
2623 a header file with these keywords, and put another copy of the
2624 definition (lacking @code{inline} and @code{extern}) in a library file.
2625 The definition in the header file will cause most calls to the function
2626 to be inlined.  If any uses of the function remain, they will refer to
2627 the single copy in the library.
2629 GNU C does not inline any functions when not optimizing.  It is not
2630 clear whether it is better to inline or not, in this case, but we found
2631 that a correct implementation when not optimizing was difficult.  So we
2632 did the easy thing, and turned it off.
2634 @node Extended Asm
2635 @section Assembler Instructions with C Expression Operands
2636 @cindex extended @code{asm}
2637 @cindex @code{asm} expressions
2638 @cindex assembler instructions
2639 @cindex registers
2641 In an assembler instruction using @code{asm}, you can specify the
2642 operands of the instruction using C expressions.  This means you need not
2643 guess which registers or memory locations will contain the data you want
2644 to use.
2646 You must specify an assembler instruction template much like what
2647 appears in a machine description, plus an operand constraint string for
2648 each operand.
2650 For example, here is how to use the 68881's @code{fsinx} instruction:
2652 @example
2653 asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
2654 @end example
2656 @noindent
2657 Here @code{angle} is the C expression for the input operand while
2658 @code{result} is that of the output operand.  Each has @samp{"f"} as its
2659 operand constraint, saying that a floating point register is required.
2660 The @samp{=} in @samp{=f} indicates that the operand is an output; all
2661 output operands' constraints must use @samp{=}.  The constraints use the
2662 same language used in the machine description (@pxref{Constraints}).
2664 Each operand is described by an operand-constraint string followed by
2665 the C expression in parentheses.  A colon separates the assembler
2666 template from the first output operand and another separates the last
2667 output operand from the first input, if any.  Commas separate the
2668 operands within each group.  The total number of operands is limited to
2669 ten or to the maximum number of operands in any instruction pattern in
2670 the machine description, whichever is greater.
2672 If there are no output operands but there are input operands, you must
2673 place two consecutive colons surrounding the place where the output
2674 operands would go.
2676 Output operand expressions must be lvalues; the compiler can check this.
2677 The input operands need not be lvalues.  The compiler cannot check
2678 whether the operands have data types that are reasonable for the
2679 instruction being executed.  It does not parse the assembler instruction
2680 template and does not know what it means or even whether it is valid
2681 assembler input.  The extended @code{asm} feature is most often used for
2682 machine instructions the compiler itself does not know exist.  If
2683 the output expression cannot be directly addressed (for example, it is a
2684 bit field), your constraint must allow a register.  In that case, GNU CC
2685 will use the register as the output of the @code{asm}, and then store
2686 that register into the output.
2688 The ordinary output operands must be write-only; GNU CC will assume that
2689 the values in these operands before the instruction are dead and need
2690 not be generated.  Extended asm supports input-output or read-write
2691 operands.  Use the constraint character @samp{+} to indicate such an
2692 operand and list it with the output operands.
2694 When the constraints for the read-write operand (or the operand in which
2695 only some of the bits are to be changed) allows a register, you may, as
2696 an alternative, logically split its function into two separate operands,
2697 one input operand and one write-only output operand.  The connection
2698 between them is expressed by constraints which say they need to be in
2699 the same location when the instruction executes.  You can use the same C
2700 expression for both operands, or different expressions.  For example,
2701 here we write the (fictitious) @samp{combine} instruction with
2702 @code{bar} as its read-only source operand and @code{foo} as its
2703 read-write destination:
2705 @example
2706 asm ("combine %2,%0" : "=r" (foo) : "0" (foo), "g" (bar));
2707 @end example
2709 @noindent
2710 The constraint @samp{"0"} for operand 1 says that it must occupy the
2711 same location as operand 0.  A digit in constraint is allowed only in an
2712 input operand and it must refer to an output operand.
2714 Only a digit in the constraint can guarantee that one operand will be in
2715 the same place as another.  The mere fact that @code{foo} is the value
2716 of both operands is not enough to guarantee that they will be in the
2717 same place in the generated assembler code.  The following would not
2718 work reliably:
2720 @example
2721 asm ("combine %2,%0" : "=r" (foo) : "r" (foo), "g" (bar));
2722 @end example
2724 Various optimizations or reloading could cause operands 0 and 1 to be in
2725 different registers; GNU CC knows no reason not to do so.  For example, the
2726 compiler might find a copy of the value of @code{foo} in one register and
2727 use it for operand 1, but generate the output operand 0 in a different
2728 register (copying it afterward to @code{foo}'s own address).  Of course,
2729 since the register for operand 1 is not even mentioned in the assembler
2730 code, the result will not work, but GNU CC can't tell that.
2732 Some instructions clobber specific hard registers.  To describe this,
2733 write a third colon after the input operands, followed by the names of
2734 the clobbered hard registers (given as strings).  Here is a realistic
2735 example for the VAX:
2737 @example
2738 asm volatile ("movc3 %0,%1,%2"
2739               : /* no outputs */
2740               : "g" (from), "g" (to), "g" (count)
2741               : "r0", "r1", "r2", "r3", "r4", "r5");
2742 @end example
2744 You may not write a clobber description in a way that overlaps with an
2745 input or output operand.  For example, you may not have an operand
2746 describing a register class with one member if you mention that register
2747 in the clobber list.  There is no way for you to specify that an input
2748 operand is modified without also specifying it as an output
2749 operand.  Note that if all the output operands you specify are for this
2750 purpose (and hence unused), you will then also need to specify
2751 @code{volatile} for the @code{asm} construct, as described below, to
2752 prevent GNU CC from deleting the @code{asm} statement as unused.
2754 If you refer to a particular hardware register from the assembler code,
2755 you will probably have to list the register after the third colon to
2756 tell the compiler the register's value is modified.  In some assemblers,
2757 the register names begin with @samp{%}; to produce one @samp{%} in the
2758 assembler code, you must write @samp{%%} in the input.
2760 If your assembler instruction can alter the condition code register, add
2761 @samp{cc} to the list of clobbered registers.  GNU CC on some machines
2762 represents the condition codes as a specific hardware register;
2763 @samp{cc} serves to name this register.  On other machines, the
2764 condition code is handled differently, and specifying @samp{cc} has no
2765 effect.  But it is valid no matter what the machine.
2767 If your assembler instruction modifies memory in an unpredictable
2768 fashion, add @samp{memory} to the list of clobbered registers.  This
2769 will cause GNU CC to not keep memory values cached in registers across
2770 the assembler instruction.  You will also want to add the
2771 @code{volatile} keyword if the memory affected is not listed in the
2772 inputs or outputs of the @code{asm}, as the @samp{memory} clobber does
2773 not count as a side-effect of the @code{asm}.
2775 You can put multiple assembler instructions together in a single
2776 @code{asm} template, separated either with newlines (written as
2777 @samp{\n}) or with semicolons if the assembler allows such semicolons.
2778 The GNU assembler allows semicolons and most Unix assemblers seem to do
2779 so.  The input operands are guaranteed not to use any of the clobbered
2780 registers, and neither will the output operands' addresses, so you can
2781 read and write the clobbered registers as many times as you like.  Here
2782 is an example of multiple instructions in a template; it assumes the
2783 subroutine @code{_foo} accepts arguments in registers 9 and 10:
2785 @example
2786 asm ("movl %0,r9;movl %1,r10;call _foo"
2787      : /* no outputs */
2788      : "g" (from), "g" (to)
2789      : "r9", "r10");
2790 @end example
2792 Unless an output operand has the @samp{&} constraint modifier, GNU CC
2793 may allocate it in the same register as an unrelated input operand, on
2794 the assumption the inputs are consumed before the outputs are produced.
2795 This assumption may be false if the assembler code actually consists of
2796 more than one instruction.  In such a case, use @samp{&} for each output
2797 operand that may not overlap an input.  @xref{Modifiers}.
2799 If you want to test the condition code produced by an assembler
2800 instruction, you must include a branch and a label in the @code{asm}
2801 construct, as follows:
2803 @example
2804 asm ("clr %0;frob %1;beq 0f;mov #1,%0;0:"
2805      : "g" (result)
2806      : "g" (input));
2807 @end example
2809 @noindent
2810 This assumes your assembler supports local labels, as the GNU assembler
2811 and most Unix assemblers do.
2813 Speaking of labels, jumps from one @code{asm} to another are not
2814 supported.  The compiler's optimizers do not know about these jumps, and
2815 therefore they cannot take account of them when deciding how to
2816 optimize.
2818 @cindex macros containing @code{asm}
2819 Usually the most convenient way to use these @code{asm} instructions is to
2820 encapsulate them in macros that look like functions.  For example,
2822 @example
2823 #define sin(x)       \
2824 (@{ double __value, __arg = (x);   \
2825    asm ("fsinx %1,%0": "=f" (__value): "f" (__arg));  \
2826    __value; @})
2827 @end example
2829 @noindent
2830 Here the variable @code{__arg} is used to make sure that the instruction
2831 operates on a proper @code{double} value, and to accept only those
2832 arguments @code{x} which can convert automatically to a @code{double}.
2834 Another way to make sure the instruction operates on the correct data
2835 type is to use a cast in the @code{asm}.  This is different from using a
2836 variable @code{__arg} in that it converts more different types.  For
2837 example, if the desired type were @code{int}, casting the argument to
2838 @code{int} would accept a pointer with no complaint, while assigning the
2839 argument to an @code{int} variable named @code{__arg} would warn about
2840 using a pointer unless the caller explicitly casts it.
2842 If an @code{asm} has output operands, GNU CC assumes for optimization
2843 purposes the instruction has no side effects except to change the output
2844 operands.  This does not mean instructions with a side effect cannot be
2845 used, but you must be careful, because the compiler may eliminate them
2846 if the output operands aren't used, or move them out of loops, or
2847 replace two with one if they constitute a common subexpression.  Also,
2848 if your instruction does have a side effect on a variable that otherwise
2849 appears not to change, the old value of the variable may be reused later
2850 if it happens to be found in a register.
2852 You can prevent an @code{asm} instruction from being deleted, moved
2853 significantly, or combined, by writing the keyword @code{volatile} after
2854 the @code{asm}.  For example:
2856 @example
2857 #define get_and_set_priority(new)  \
2858 (@{ int __old; \
2859    asm volatile ("get_and_set_priority %0, %1": "=g" (__old) : "g" (new)); \
2860    __old; @})
2861 @end example
2863 @noindent
2864 If you write an @code{asm} instruction with no outputs, GNU CC will know
2865 the instruction has side-effects and will not delete the instruction or
2866 move it outside of loops.  If the side-effects of your instruction are
2867 not purely external, but will affect variables in your program in ways
2868 other than reading the inputs and clobbering the specified registers or
2869 memory, you should write the @code{volatile} keyword to prevent future
2870 versions of GNU CC from moving the instruction around within a core
2871 region.
2873 An @code{asm} instruction without any operands or clobbers (and ``old
2874 style'' @code{asm}) will not be deleted or moved significantly,
2875 regardless, unless it is unreachable, the same way as if you had
2876 written a @code{volatile} keyword.
2878 Note that even a volatile @code{asm} instruction can be moved in ways
2879 that appear insignificant to the compiler, such as across jump
2880 instructions.  You can't expect a sequence of volatile @code{asm}
2881 instructions to remain perfectly consecutive.  If you want consecutive
2882 output, use a single @code{asm}.
2884 It is a natural idea to look for a way to give access to the condition
2885 code left by the assembler instruction.  However, when we attempted to
2886 implement this, we found no way to make it work reliably.  The problem
2887 is that output operands might need reloading, which would result in
2888 additional following ``store'' instructions.  On most machines, these
2889 instructions would alter the condition code before there was time to
2890 test it.  This problem doesn't arise for ordinary ``test'' and
2891 ``compare'' instructions because they don't have any output operands.
2893 For reasons similar to those described above, it is not possible to give
2894 an assembler instruction access to the condition code left by previous
2895 instructions.
2897 If you are writing a header file that should be includable in ISO C
2898 programs, write @code{__asm__} instead of @code{asm}.  @xref{Alternate
2899 Keywords}.
2901 @subsection i386 floating point asm operands
2903 There are several rules on the usage of stack-like regs in
2904 asm_operands insns.  These rules apply only to the operands that are
2905 stack-like regs:
2907 @enumerate
2908 @item
2909 Given a set of input regs that die in an asm_operands, it is
2910 necessary to know which are implicitly popped by the asm, and
2911 which must be explicitly popped by gcc.
2913 An input reg that is implicitly popped by the asm must be
2914 explicitly clobbered, unless it is constrained to match an
2915 output operand.
2917 @item
2918 For any input reg that is implicitly popped by an asm, it is
2919 necessary to know how to adjust the stack to compensate for the pop.
2920 If any non-popped input is closer to the top of the reg-stack than
2921 the implicitly popped reg, it would not be possible to know what the
2922 stack looked like --- it's not clear how the rest of the stack ``slides
2923 up''.
2925 All implicitly popped input regs must be closer to the top of
2926 the reg-stack than any input that is not implicitly popped.
2928 It is possible that if an input dies in an insn, reload might
2929 use the input reg for an output reload.  Consider this example:
2931 @example
2932 asm ("foo" : "=t" (a) : "f" (b));
2933 @end example
2935 This asm says that input B is not popped by the asm, and that
2936 the asm pushes a result onto the reg-stack, ie, the stack is one
2937 deeper after the asm than it was before.  But, it is possible that
2938 reload will think that it can use the same reg for both the input and
2939 the output, if input B dies in this insn.
2941 If any input operand uses the @code{f} constraint, all output reg
2942 constraints must use the @code{&} earlyclobber.
2944 The asm above would be written as
2946 @example
2947 asm ("foo" : "=&t" (a) : "f" (b));
2948 @end example
2950 @item
2951 Some operands need to be in particular places on the stack.  All
2952 output operands fall in this category --- there is no other way to
2953 know which regs the outputs appear in unless the user indicates
2954 this in the constraints.
2956 Output operands must specifically indicate which reg an output
2957 appears in after an asm.  @code{=f} is not allowed: the operand
2958 constraints must select a class with a single reg.
2960 @item
2961 Output operands may not be ``inserted'' between existing stack regs.
2962 Since no 387 opcode uses a read/write operand, all output operands
2963 are dead before the asm_operands, and are pushed by the asm_operands.
2964 It makes no sense to push anywhere but the top of the reg-stack.
2966 Output operands must start at the top of the reg-stack: output
2967 operands may not ``skip'' a reg.
2969 @item
2970 Some asm statements may need extra stack space for internal
2971 calculations.  This can be guaranteed by clobbering stack registers
2972 unrelated to the inputs and outputs.
2974 @end enumerate
2976 Here are a couple of reasonable asms to want to write.  This asm
2977 takes one input, which is internally popped, and produces two outputs.
2979 @example
2980 asm ("fsincos" : "=t" (cos), "=u" (sin) : "0" (inp));
2981 @end example
2983 This asm takes two inputs, which are popped by the @code{fyl2xp1} opcode,
2984 and replaces them with one output.  The user must code the @code{st(1)}
2985 clobber for reg-stack.c to know that @code{fyl2xp1} pops both inputs.
2987 @example
2988 asm ("fyl2xp1" : "=t" (result) : "0" (x), "u" (y) : "st(1)");
2989 @end example
2991 @ifclear INTERNALS
2992 @c Show the details on constraints if they do not appear elsewhere in
2993 @c the manual
2994 @include md.texi
2995 @end ifclear
2997 @node Asm Labels
2998 @section Controlling Names Used in Assembler Code
2999 @cindex assembler names for identifiers
3000 @cindex names used in assembler code
3001 @cindex identifiers, names in assembler code
3003 You can specify the name to be used in the assembler code for a C
3004 function or variable by writing the @code{asm} (or @code{__asm__})
3005 keyword after the declarator as follows:
3007 @example
3008 int foo asm ("myfoo") = 2;
3009 @end example
3011 @noindent
3012 This specifies that the name to be used for the variable @code{foo} in
3013 the assembler code should be @samp{myfoo} rather than the usual
3014 @samp{_foo}.
3016 On systems where an underscore is normally prepended to the name of a C
3017 function or variable, this feature allows you to define names for the
3018 linker that do not start with an underscore.
3020 You cannot use @code{asm} in this way in a function @emph{definition}; but
3021 you can get the same effect by writing a declaration for the function
3022 before its definition and putting @code{asm} there, like this:
3024 @example
3025 extern func () asm ("FUNC");
3027 func (x, y)
3028      int x, y;
3029 @dots{}
3030 @end example
3032 It is up to you to make sure that the assembler names you choose do not
3033 conflict with any other assembler symbols.  Also, you must not use a
3034 register name; that would produce completely invalid assembler code.  GNU
3035 CC does not as yet have the ability to store static variables in registers.
3036 Perhaps that will be added.
3038 @node Explicit Reg Vars
3039 @section Variables in Specified Registers
3040 @cindex explicit register variables
3041 @cindex variables in specified registers
3042 @cindex specified registers
3043 @cindex registers, global allocation
3045 GNU C allows you to put a few global variables into specified hardware
3046 registers.  You can also specify the register in which an ordinary
3047 register variable should be allocated.
3049 @itemize @bullet
3050 @item
3051 Global register variables reserve registers throughout the program.
3052 This may be useful in programs such as programming language
3053 interpreters which have a couple of global variables that are accessed
3054 very often.
3056 @item
3057 Local register variables in specific registers do not reserve the
3058 registers.  The compiler's data flow analysis is capable of determining
3059 where the specified registers contain live values, and where they are
3060 available for other uses.  Stores into local register variables may be deleted
3061 when they appear to be dead according to dataflow analysis.  References
3062 to local register variables may be deleted or moved or simplified.
3064 These local variables are sometimes convenient for use with the extended
3065 @code{asm} feature (@pxref{Extended Asm}), if you want to write one
3066 output of the assembler instruction directly into a particular register.
3067 (This will work provided the register you specify fits the constraints
3068 specified for that operand in the @code{asm}.)
3069 @end itemize
3071 @menu
3072 * Global Reg Vars::
3073 * Local Reg Vars::
3074 @end menu
3076 @node Global Reg Vars
3077 @subsection Defining Global Register Variables
3078 @cindex global register variables
3079 @cindex registers, global variables in
3081 You can define a global register variable in GNU C like this:
3083 @example
3084 register int *foo asm ("a5");
3085 @end example
3087 @noindent
3088 Here @code{a5} is the name of the register which should be used.  Choose a
3089 register which is normally saved and restored by function calls on your
3090 machine, so that library routines will not clobber it.
3092 Naturally the register name is cpu-dependent, so you would need to
3093 conditionalize your program according to cpu type.  The register
3094 @code{a5} would be a good choice on a 68000 for a variable of pointer
3095 type.  On machines with register windows, be sure to choose a ``global''
3096 register that is not affected magically by the function call mechanism.
3098 In addition, operating systems on one type of cpu may differ in how they
3099 name the registers; then you would need additional conditionals.  For
3100 example, some 68000 operating systems call this register @code{%a5}.
3102 Eventually there may be a way of asking the compiler to choose a register
3103 automatically, but first we need to figure out how it should choose and
3104 how to enable you to guide the choice.  No solution is evident.
3106 Defining a global register variable in a certain register reserves that
3107 register entirely for this use, at least within the current compilation.
3108 The register will not be allocated for any other purpose in the functions
3109 in the current compilation.  The register will not be saved and restored by
3110 these functions.  Stores into this register are never deleted even if they
3111 would appear to be dead, but references may be deleted or moved or
3112 simplified.
3114 It is not safe to access the global register variables from signal
3115 handlers, or from more than one thread of control, because the system
3116 library routines may temporarily use the register for other things (unless
3117 you recompile them specially for the task at hand).
3119 @cindex @code{qsort}, and global register variables
3120 It is not safe for one function that uses a global register variable to
3121 call another such function @code{foo} by way of a third function
3122 @code{lose} that was compiled without knowledge of this variable (i.e. in a
3123 different source file in which the variable wasn't declared).  This is
3124 because @code{lose} might save the register and put some other value there.
3125 For example, you can't expect a global register variable to be available in
3126 the comparison-function that you pass to @code{qsort}, since @code{qsort}
3127 might have put something else in that register.  (If you are prepared to
3128 recompile @code{qsort} with the same global register variable, you can
3129 solve this problem.)
3131 If you want to recompile @code{qsort} or other source files which do not
3132 actually use your global register variable, so that they will not use that
3133 register for any other purpose, then it suffices to specify the compiler
3134 option @samp{-ffixed-@var{reg}}.  You need not actually add a global
3135 register declaration to their source code.
3137 A function which can alter the value of a global register variable cannot
3138 safely be called from a function compiled without this variable, because it
3139 could clobber the value the caller expects to find there on return.
3140 Therefore, the function which is the entry point into the part of the
3141 program that uses the global register variable must explicitly save and
3142 restore the value which belongs to its caller.
3144 @cindex register variable after @code{longjmp}
3145 @cindex global register after @code{longjmp}
3146 @cindex value after @code{longjmp}
3147 @findex longjmp
3148 @findex setjmp
3149 On most machines, @code{longjmp} will restore to each global register
3150 variable the value it had at the time of the @code{setjmp}.  On some
3151 machines, however, @code{longjmp} will not change the value of global
3152 register variables.  To be portable, the function that called @code{setjmp}
3153 should make other arrangements to save the values of the global register
3154 variables, and to restore them in a @code{longjmp}.  This way, the same
3155 thing will happen regardless of what @code{longjmp} does.
3157 All global register variable declarations must precede all function
3158 definitions.  If such a declaration could appear after function
3159 definitions, the declaration would be too late to prevent the register from
3160 being used for other purposes in the preceding functions.
3162 Global register variables may not have initial values, because an
3163 executable file has no means to supply initial contents for a register.
3165 On the Sparc, there are reports that g3 @dots{} g7 are suitable
3166 registers, but certain library functions, such as @code{getwd}, as well
3167 as the subroutines for division and remainder, modify g3 and g4.  g1 and
3168 g2 are local temporaries.
3170 On the 68000, a2 @dots{} a5 should be suitable, as should d2 @dots{} d7.
3171 Of course, it will not do to use more than a few of those.
3173 @node Local Reg Vars
3174 @subsection Specifying Registers for Local Variables
3175 @cindex local variables, specifying registers
3176 @cindex specifying registers for local variables
3177 @cindex registers for local variables
3179 You can define a local register variable with a specified register
3180 like this:
3182 @example
3183 register int *foo asm ("a5");
3184 @end example
3186 @noindent
3187 Here @code{a5} is the name of the register which should be used.  Note
3188 that this is the same syntax used for defining global register
3189 variables, but for a local variable it would appear within a function.
3191 Naturally the register name is cpu-dependent, but this is not a
3192 problem, since specific registers are most often useful with explicit
3193 assembler instructions (@pxref{Extended Asm}).  Both of these things
3194 generally require that you conditionalize your program according to
3195 cpu type.
3197 In addition, operating systems on one type of cpu may differ in how they
3198 name the registers; then you would need additional conditionals.  For
3199 example, some 68000 operating systems call this register @code{%a5}.
3201 Defining such a register variable does not reserve the register; it
3202 remains available for other uses in places where flow control determines
3203 the variable's value is not live.  However, these registers are made
3204 unavailable for use in the reload pass; excessive use of this feature
3205 leaves the compiler too few available registers to compile certain
3206 functions.
3208 This option does not guarantee that GNU CC will generate code that has
3209 this variable in the register you specify at all times.  You may not
3210 code an explicit reference to this register in an @code{asm} statement
3211 and assume it will always refer to this variable.
3213 Stores into local register variables may be deleted when they appear to be dead
3214 according to dataflow analysis.  References to local register variables may
3215 be deleted or moved or simplified.
3217 @node Alternate Keywords
3218 @section Alternate Keywords
3219 @cindex alternate keywords
3220 @cindex keywords, alternate
3222 The option @option{-traditional} disables certain keywords;
3223 @option{-ansi} and the various @option{-std} options disable certain
3224 others.  This causes trouble when you want to use GNU C extensions, or
3225 ISO C features, in a general-purpose header file that should be usable
3226 by all programs, including ISO C programs and traditional ones.  The
3227 keywords @code{asm}, @code{typeof} and @code{inline} cannot be used
3228 since they won't work in a program compiled with @option{-ansi}
3229 (although @code{inline} can be used in a program compiled with
3230 @option{-std=c99}), while the keywords @code{const}, @code{volatile},
3231 @code{signed}, @code{typeof} and @code{inline} won't work in a program
3232 compiled with @option{-traditional}.  The ISO C99 keyword
3233 @code{restrict} is only available when @option{-std=gnu99} (which will
3234 eventually be the default) or @option{-std=c99} (or the equivalent
3235 @option{-std=iso9899:1999}) is used.@refill
3237 The way to solve these problems is to put @samp{__} at the beginning and
3238 end of each problematical keyword.  For example, use @code{__asm__}
3239 instead of @code{asm}, @code{__const__} instead of @code{const}, and
3240 @code{__inline__} instead of @code{inline}.
3242 Other C compilers won't accept these alternative keywords; if you want to
3243 compile with another compiler, you can define the alternate keywords as
3244 macros to replace them with the customary keywords.  It looks like this:
3246 @example
3247 #ifndef __GNUC__
3248 #define __asm__ asm
3249 #endif
3250 @end example
3252 @findex __extension__
3253 @samp{-pedantic} and other options cause warnings for many GNU C extensions.
3254 You can
3255 prevent such warnings within one expression by writing
3256 @code{__extension__} before the expression.  @code{__extension__} has no
3257 effect aside from this.
3259 @node Incomplete Enums
3260 @section Incomplete @code{enum} Types
3262 You can define an @code{enum} tag without specifying its possible values.
3263 This results in an incomplete type, much like what you get if you write
3264 @code{struct foo} without describing the elements.  A later declaration
3265 which does specify the possible values completes the type.
3267 You can't allocate variables or storage using the type while it is
3268 incomplete.  However, you can work with pointers to that type.
3270 This extension may not be very useful, but it makes the handling of
3271 @code{enum} more consistent with the way @code{struct} and @code{union}
3272 are handled.
3274 This extension is not supported by GNU C++.
3276 @node Function Names
3277 @section Function Names as Strings
3279 GNU CC predefines two magic identifiers to hold the name of the current
3280 function. The identifier @code{__FUNCTION__} holds the name of the function
3281 as it appears in the source. The identifier @code{__PRETTY_FUNCTION__}
3282 holds the name of the function pretty printed in a language specific
3283 fashion.
3285 These names are always the same in a C function, but in a C++ function
3286 they may be different.  For example, this program:
3288 @smallexample
3289 extern "C" @{
3290 extern int printf (char *, ...);
3293 class a @{
3294  public:
3295   sub (int i)
3296     @{
3297       printf ("__FUNCTION__ = %s\n", __FUNCTION__);
3298       printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
3299     @}
3303 main (void)
3305   a ax;
3306   ax.sub (0);
3307   return 0;
3309 @end smallexample
3311 @noindent
3312 gives this output:
3314 @smallexample
3315 __FUNCTION__ = sub
3316 __PRETTY_FUNCTION__ = int  a::sub (int)
3317 @end smallexample
3319 The compiler automagically replaces the identifiers with a string
3320 literal containing the appropriate name. Thus, they are neither
3321 preprocessor macros, like @code{__FILE__} and @code{__LINE__}, nor
3322 variables. This means that they catenate with other string literals, and
3323 that they can be used to initialize char arrays. For example
3325 @smallexample
3326 char here[] = "Function " __FUNCTION__ " in " __FILE__;
3327 @end smallexample
3329 On the other hand, @samp{#ifdef __FUNCTION__} does not have any special
3330 meaning inside a function, since the preprocessor does not do anything
3331 special with the identifier @code{__FUNCTION__}.
3333 GNU CC also supports the magic word @code{__func__}, defined by the
3334 ISO standard C-99:
3336 @display
3337 The identifier @code{__func__} is implicitly declared by the translator
3338 as if, immediately following the opening brace of each function
3339 definition, the declaration
3341 @smallexample
3342 static const char __func__[] = "function-name";
3343 @end smallexample
3345 appeared, where function-name is the name of the lexically-enclosing
3346 function. This name is the unadorned name of the function.
3347 @end display
3349 By this definition, @code{__func__} is a variable, not a string literal.
3350 In particular, @code{__func__} does not catenate with other string
3351 literals.
3353 In @code{C++}, @code{__FUNCTION__} and @code{__PRETTY_FUNCTION__} are
3354 variables, declared in the same way as @code{__func__}.
3356 @node Return Address
3357 @section Getting the Return or Frame Address of a Function
3359 These functions may be used to get information about the callers of a
3360 function.
3362 @table @code
3363 @findex __builtin_return_address
3364 @item __builtin_return_address (@var{level})
3365 This function returns the return address of the current function, or of
3366 one of its callers.  The @var{level} argument is number of frames to
3367 scan up the call stack.  A value of @code{0} yields the return address
3368 of the current function, a value of @code{1} yields the return address
3369 of the caller of the current function, and so forth.
3371 The @var{level} argument must be a constant integer.
3373 On some machines it may be impossible to determine the return address of
3374 any function other than the current one; in such cases, or when the top
3375 of the stack has been reached, this function will return @code{0}.
3377 This function should only be used with a non-zero argument for debugging
3378 purposes.
3380 @findex __builtin_frame_address
3381 @item __builtin_frame_address (@var{level})
3382 This function is similar to @code{__builtin_return_address}, but it
3383 returns the address of the function frame rather than the return address
3384 of the function.  Calling @code{__builtin_frame_address} with a value of
3385 @code{0} yields the frame address of the current function, a value of
3386 @code{1} yields the frame address of the caller of the current function,
3387 and so forth.
3389 The frame is the area on the stack which holds local variables and saved
3390 registers.  The frame address is normally the address of the first word
3391 pushed on to the stack by the function.  However, the exact definition
3392 depends upon the processor and the calling convention.  If the processor
3393 has a dedicated frame pointer register, and the function has a frame,
3394 then @code{__builtin_frame_address} will return the value of the frame
3395 pointer register.
3397 The caveats that apply to @code{__builtin_return_address} apply to this
3398 function as well.
3399 @end table
3401 @node Other Builtins
3402 @section Other built-in functions provided by GNU CC
3403 @cindex builtin functions
3404 @findex __builtin_isgreater
3405 @findex __builtin_isgreaterequal
3406 @findex __builtin_isless
3407 @findex __builtin_islessequal
3408 @findex __builtin_islessgreater
3409 @findex __builtin_isunordered
3410 @findex abort
3411 @findex abs
3412 @findex alloca
3413 @findex bcmp
3414 @findex bzero
3415 @findex cimag
3416 @findex cimagf
3417 @findex cimagl
3418 @findex conj
3419 @findex conjf
3420 @findex conjl
3421 @findex cos
3422 @findex cosf
3423 @findex cosl
3424 @findex creal
3425 @findex crealf
3426 @findex creall
3427 @findex exit
3428 @findex _exit
3429 @findex _Exit
3430 @findex fabs
3431 @findex fabsf
3432 @findex fabsl
3433 @findex ffs
3434 @findex fprintf
3435 @findex fputs
3436 @findex imaxabs
3437 @findex index
3438 @findex labs
3439 @findex llabs
3440 @findex memcmp
3441 @findex memcpy
3442 @findex memset
3443 @findex printf
3444 @findex rindex
3445 @findex sin
3446 @findex sinf
3447 @findex sinl
3448 @findex sqrt
3449 @findex sqrtf
3450 @findex sqrtl
3451 @findex strcat
3452 @findex strchr
3453 @findex strcmp
3454 @findex strcpy
3455 @findex strcspn
3456 @findex strlen
3457 @findex strncat
3458 @findex strncmp
3459 @findex strncpy
3460 @findex strpbrk
3461 @findex strrchr
3462 @findex strspn
3463 @findex strstr
3465 GNU CC provides a large number of built-in functions other than the ones
3466 mentioned above.  Some of these are for internal use in the processing
3467 of exceptions or variable-length argument lists and will not be
3468 documented here because they may change from time to time; we do not
3469 recommend general use of these functions.
3471 The remaining functions are provided for optimization purposes.
3473 GNU CC includes builtin versions of many of the functions in the
3474 standard C library.  The versions prefixed with @code{__builtin_} will
3475 always be treated as having the same meaning as the C library function
3476 even if you specify the @samp{-fno-builtin} (@pxref{C Dialect Options})
3477 option.  Many of these functions are only optimized in certain cases; if
3478 not optimized in a particular case, a call to the library function will
3479 be emitted.
3481 The functions @code{abort}, @code{exit}, @code{_Exit} and @code{_exit}
3482 are recognized and presumed not to return, but otherwise are not built
3483 in.  @code{_exit} is not recognized in strict ISO C mode (@samp{-ansi},
3484 @samp{-std=c89} or @samp{-std=c99}).  @code{_Exit} is not recognized in
3485 strict C89 mode (@samp{-ansi} or @samp{-std=c89}).
3487 Outside strict ISO C mode, the functions @code{alloca}, @code{bcmp},
3488 @code{bzero}, @code{index}, @code{rindex} and @code{ffs} may be handled
3489 as builtins.  Corresponding versions @code{__builtin_alloca},
3490 @code{__builtin_bcmp}, @code{__builtin_bzero}, @code{__builtin_index},
3491 @code{__builtin_rindex} and @code{__builtin_ffs} are also recognized in
3492 strict ISO C mode.
3494 The ISO C99 functions @code{conj}, @code{conjf}, @code{conjl},
3495 @code{creal}, @code{crealf}, @code{creall}, @code{cimag}, @code{cimagf},
3496 @code{cimagl}, @code{llabs} and @code{imaxabs} are handled as builtins
3497 except in strict ISO C89 mode.  There are also builtin versions of the ISO C99
3498 functions @code{cosf}, @code{cosl}, @code{fabsf}, @code{fabsl},
3499 @code{sinf}, @code{sinl}, @code{sqrtf}, and @code{sqrtl}, that are
3500 recognized in any mode since ISO C89 reserves these names for the
3501 purpose to which ISO C99 puts them.  All these functions have
3502 corresponding versions prefixed with @code{__builtin_}.
3504 The following ISO C89 functions are recognized as builtins unless
3505 @samp{-fno-builtin} is specified: @code{abs}, @code{cos}, @code{fabs},
3506 @code{fprintf}, @code{fputs}, @code{labs}, @code{memcmp}, @code{memcpy},
3507 @code{memset}, @code{printf}, @code{sin}, @code{sqrt}, @code{strcat},
3508 @code{strchr}, @code{strcmp}, @code{strcpy}, @code{strcspn},
3509 @code{strlen}, @code{strncat}, @code{strncmp}, @code{strncpy},
3510 @code{strpbrk}, @code{strrchr}, @code{strspn}, and @code{strstr}.  All
3511 of these functions have corresponding versions prefixed with
3512 @code{__builtin_}, except that the version for @code{sqrt} is called
3513 @code{__builtin_fsqrt}.
3515 GNU CC provides builtin versions of the ISO C99 floating point
3516 comparison macros (that avoid raising exceptions for unordered
3517 operands): @code{__builtin_isgreater}, @code{__builtin_isgreaterequal},
3518 @code{__builtin_isless}, @code{__builtin_islessequal},
3519 @code{__builtin_islessgreater}, and @code{__builtin_isunordered}.
3522 @table @code
3523 @findex __builtin_constant_p
3524 @item __builtin_constant_p (@var{exp})
3525 You can use the builtin function @code{__builtin_constant_p} to
3526 determine if a value is known to be constant at compile-time and hence
3527 that GNU CC can perform constant-folding on expressions involving that
3528 value.  The argument of the function is the value to test.  The function
3529 returns the integer 1 if the argument is known to be a compile-time
3530 constant and 0 if it is not known to be a compile-time constant.  A
3531 return of 0 does not indicate that the value is @emph{not} a constant,
3532 but merely that GNU CC cannot prove it is a constant with the specified
3533 value of the @samp{-O} option.
3535 You would typically use this function in an embedded application where
3536 memory was a critical resource.  If you have some complex calculation,
3537 you may want it to be folded if it involves constants, but need to call
3538 a function if it does not.  For example:
3540 @smallexample
3541 #define Scale_Value(X)  \
3542   (__builtin_constant_p (X) ? ((X) * SCALE + OFFSET) : Scale (X))
3543 @end smallexample
3545 You may use this builtin function in either a macro or an inline
3546 function.  However, if you use it in an inlined function and pass an
3547 argument of the function as the argument to the builtin, GNU CC will
3548 never return 1 when you call the inline function with a string constant
3549 or constructor expression (@pxref{Constructors}) and will not return 1
3550 when you pass a constant numeric value to the inline function unless you
3551 specify the @samp{-O} option.
3553 @findex __builtin_expect
3554 @item __builtin_expect(@var{exp}, @var{c})
3555 You may use @code{__builtin_expect} to provide the compiler with 
3556 branch prediction information.  In general, you should prefer to
3557 use actual profile feedback for this (@samp{-fprofile-arcs}), as
3558 programmers are notoriously bad at predicting how their programs
3559 actually perform.  However, there are applications in which this
3560 data is hard to collect.
3562 The return value is the value of @var{exp}, which should be an
3563 integral expression.  The value of @var{c} must be a compile-time
3564 constant.  The semantics of the builtin are that it is expected
3565 that @var{exp} == @var{c}.  For example:
3567 @smallexample
3568 if (__builtin_expect (x, 0))
3569   foo ();
3570 @end smallexample
3572 @noindent
3573 would indicate that we do not expect to call @code{foo}, since
3574 we expect @code{x} to be zero.  Since you are limited to integral
3575 expressions for @var{exp}, you should use constructions such as
3577 @smallexample
3578 if (__builtin_expect (ptr != NULL, 1))
3579   error ();
3580 @end smallexample
3582 @noindent
3583 when testing pointer or floating-point values.
3584 @end table
3586 @node C++ Extensions
3587 @chapter Extensions to the C++ Language
3588 @cindex extensions, C++ language
3589 @cindex C++ language extensions
3591 The GNU compiler provides these extensions to the C++ language (and you
3592 can also use most of the C language extensions in your C++ programs).  If you
3593 want to write code that checks whether these features are available, you can
3594 test for the GNU compiler the same way as for C programs: check for a
3595 predefined macro @code{__GNUC__}.  You can also use @code{__GNUG__} to
3596 test specifically for GNU C++ (@pxref{Standard Predefined,,Standard
3597 Predefined Macros,cpp.info,The C Preprocessor}).
3599 @menu
3600 * Min and Max::         C++ Minimum and maximum operators.
3601 * Volatiles::           What constitutes an access to a volatile object.
3602 * Restricted Pointers:: C99 restricted pointers and references.
3603 * C++ Interface::       You can use a single C++ header file for both
3604                         declarations and definitions.
3605 * Template Instantiation:: Methods for ensuring that exactly one copy of
3606                         each needed template instantiation is emitted.
3607 * Bound member functions:: You can extract a function pointer to the
3608                         method denoted by a @samp{->*} or @samp{.*} expression.
3609 * C++ Attributes::      Variable, function, and type attributes for C++ only.
3610 * Deprecated Features:: Things might disappear from g++.
3611 * Backwards Compatibility:: Compatibilities with earlier definitions of C++.
3612 @end menu
3614 @node Min and Max
3615 @section Minimum and Maximum Operators in C++
3617 It is very convenient to have operators which return the ``minimum'' or the
3618 ``maximum'' of two arguments.  In GNU C++ (but not in GNU C),
3620 @table @code
3621 @item @var{a} <? @var{b}
3622 @findex <?
3623 @cindex minimum operator
3624 is the @dfn{minimum}, returning the smaller of the numeric values
3625 @var{a} and @var{b};
3627 @item @var{a} >? @var{b}
3628 @findex >?
3629 @cindex maximum operator
3630 is the @dfn{maximum}, returning the larger of the numeric values @var{a}
3631 and @var{b}.
3632 @end table
3634 These operations are not primitive in ordinary C++, since you can
3635 use a macro to return the minimum of two things in C++, as in the
3636 following example.
3638 @example
3639 #define MIN(X,Y) ((X) < (Y) ? : (X) : (Y))
3640 @end example
3642 @noindent
3643 You might then use @w{@samp{int min = MIN (i, j);}} to set @var{min} to
3644 the minimum value of variables @var{i} and @var{j}.
3646 However, side effects in @code{X} or @code{Y} may cause unintended
3647 behavior.  For example, @code{MIN (i++, j++)} will fail, incrementing
3648 the smaller counter twice.  A GNU C extension allows you to write safe
3649 macros that avoid this kind of problem (@pxref{Naming Types,,Naming an
3650 Expression's Type}).  However, writing @code{MIN} and @code{MAX} as
3651 macros also forces you to use function-call notation for a
3652 fundamental arithmetic operation.  Using GNU C++ extensions, you can
3653 write @w{@samp{int min = i <? j;}} instead.
3655 Since @code{<?} and @code{>?} are built into the compiler, they properly
3656 handle expressions with side-effects;  @w{@samp{int min = i++ <? j++;}}
3657 works correctly.
3659 @node Volatiles
3660 @section When is a Volatile Object Accessed?
3661 @cindex accessing volatiles
3662 @cindex volatile read
3663 @cindex volatile write
3664 @cindex volatile access
3666 Both the C and C++ standard have the concept of volatile objects. These
3667 are normally accessed by pointers and used for accessing hardware. The
3668 standards encourage compilers to refrain from optimizations
3669 concerning accesses to volatile objects that it might perform on
3670 non-volatile objects. The C standard leaves it implementation defined
3671 as to what constitutes a volatile access. The C++ standard omits to
3672 specify this, except to say that C++ should behave in a similar manner
3673 to C with respect to volatiles, where possible. The minimum either
3674 standard specifies is that at a sequence point all previous accesses to
3675 volatile objects have stabilized and no subsequent accesses have
3676 occurred. Thus an implementation is free to reorder and combine
3677 volatile accesses which occur between sequence points, but cannot do so
3678 for accesses across a sequence point. The use of volatiles does not
3679 allow you to violate the restriction on updating objects multiple times
3680 within a sequence point.
3682 In most expressions, it is intuitively obvious what is a read and what is
3683 a write. For instance
3685 @example
3686 volatile int *dst = <somevalue>;
3687 volatile int *src = <someothervalue>;
3688 *dst = *src;
3689 @end example
3691 @noindent
3692 will cause a read of the volatile object pointed to by @var{src} and stores the
3693 value into the volatile object pointed to by @var{dst}. There is no
3694 guarantee that these reads and writes are atomic, especially for objects
3695 larger than @code{int}.
3697 Less obvious expressions are where something which looks like an access
3698 is used in a void context. An example would be,
3700 @example
3701 volatile int *src = <somevalue>;
3702 *src;
3703 @end example
3705 With C, such expressions are rvalues, and as rvalues cause a read of
3706 the object, gcc interprets this as a read of the volatile being pointed
3707 to. The C++ standard specifies that such expressions do not undergo
3708 lvalue to rvalue conversion, and that the type of the dereferenced
3709 object may be incomplete. The C++ standard does not specify explicitly
3710 that it is this lvalue to rvalue conversion which is responsible for
3711 causing an access. However, there is reason to believe that it is,
3712 because otherwise certain simple expressions become undefined. However,
3713 because it would surprise most programmers, g++ treats dereferencing a
3714 pointer to volatile object of complete type in a void context as a read
3715 of the object. When the object has incomplete type, g++ issues a
3716 warning.
3718 @example
3719 struct S;
3720 struct T @{int m;@};
3721 volatile S *ptr1 = <somevalue>;
3722 volatile T *ptr2 = <somevalue>;
3723 *ptr1;
3724 *ptr2;
3725 @end example
3727 In this example, a warning is issued for @code{*ptr1}, and @code{*ptr2}
3728 causes a read of the object pointed to. If you wish to force an error on
3729 the first case, you must force a conversion to rvalue with, for instance
3730 a static cast, @code{static_cast<S>(*ptr1)}.
3732 When using a reference to volatile, g++ does not treat equivalent
3733 expressions as accesses to volatiles, but instead issues a warning that
3734 no volatile is accessed. The rationale for this is that otherwise it
3735 becomes difficult to determine where volatile access occur, and not
3736 possible to ignore the return value from functions returning volatile
3737 references. Again, if you wish to force a read, cast the reference to
3738 an rvalue.
3740 @node Restricted Pointers
3741 @section Restricting Pointer Aliasing
3742 @cindex restricted pointers
3743 @cindex restricted references
3744 @cindex restricted this pointer
3746 As with gcc, g++ understands the C99 feature of restricted pointers,
3747 specified with the @code{__restrict__}, or @code{__restrict} type
3748 qualifier. Because you cannot compile C++ by specifying the -std=c99
3749 language flag, @code{restrict} is not a keyword in C++.
3751 In addition to allowing restricted pointers, you can specify restricted
3752 references, which indicate that the reference is not aliased in the local
3753 context.
3755 @example
3756 void fn (int *__restrict__ rptr, int &__restrict__ rref)
3758   @dots{}
3760 @end example
3762 @noindent
3763 In the body of @code{fn}, @var{rptr} points to an unaliased integer and
3764 @var{rref} refers to a (different) unaliased integer.
3766 You may also specify whether a member function's @var{this} pointer is
3767 unaliased by using @code{__restrict__} as a member function qualifier.
3769 @example
3770 void T::fn () __restrict__
3772   @dots{}
3774 @end example
3776 @noindent
3777 Within the body of @code{T::fn}, @var{this} will have the effective
3778 definition @code{T *__restrict__ const this}. Notice that the
3779 interpretation of a @code{__restrict__} member function qualifier is
3780 different to that of @code{const} or @code{volatile} qualifier, in that it
3781 is applied to the pointer rather than the object. This is consistent with
3782 other compilers which implement restricted pointers.
3784 As with all outermost parameter qualifiers, @code{__restrict__} is
3785 ignored in function definition matching. This means you only need to
3786 specify @code{__restrict__} in a function definition, rather than
3787 in a function prototype as well.
3789 @node C++ Interface
3790 @section Declarations and Definitions in One Header
3792 @cindex interface and implementation headers, C++
3793 @cindex C++ interface and implementation headers
3794 C++ object definitions can be quite complex.  In principle, your source
3795 code will need two kinds of things for each object that you use across
3796 more than one source file.  First, you need an @dfn{interface}
3797 specification, describing its structure with type declarations and
3798 function prototypes.  Second, you need the @dfn{implementation} itself.
3799 It can be tedious to maintain a separate interface description in a
3800 header file, in parallel to the actual implementation.  It is also
3801 dangerous, since separate interface and implementation definitions may
3802 not remain parallel.
3804 @cindex pragmas, interface and implementation
3805 With GNU C++, you can use a single header file for both purposes.
3807 @quotation
3808 @emph{Warning:} The mechanism to specify this is in transition.  For the
3809 nonce, you must use one of two @code{#pragma} commands; in a future
3810 release of GNU C++, an alternative mechanism will make these
3811 @code{#pragma} commands unnecessary.
3812 @end quotation
3814 The header file contains the full definitions, but is marked with
3815 @samp{#pragma interface} in the source code.  This allows the compiler
3816 to use the header file only as an interface specification when ordinary
3817 source files incorporate it with @code{#include}.  In the single source
3818 file where the full implementation belongs, you can use either a naming
3819 convention or @samp{#pragma implementation} to indicate this alternate
3820 use of the header file.
3822 @table @code
3823 @item #pragma interface
3824 @itemx #pragma interface "@var{subdir}/@var{objects}.h"
3825 @kindex #pragma interface
3826 Use this directive in @emph{header files} that define object classes, to save
3827 space in most of the object files that use those classes.  Normally,
3828 local copies of certain information (backup copies of inline member
3829 functions, debugging information, and the internal tables that implement
3830 virtual functions) must be kept in each object file that includes class
3831 definitions.  You can use this pragma to avoid such duplication.  When a
3832 header file containing @samp{#pragma interface} is included in a
3833 compilation, this auxiliary information will not be generated (unless
3834 the main input source file itself uses @samp{#pragma implementation}).
3835 Instead, the object files will contain references to be resolved at link
3836 time.
3838 The second form of this directive is useful for the case where you have
3839 multiple headers with the same name in different directories.  If you
3840 use this form, you must specify the same string to @samp{#pragma
3841 implementation}.
3843 @item #pragma implementation
3844 @itemx #pragma implementation "@var{objects}.h"
3845 @kindex #pragma implementation
3846 Use this pragma in a @emph{main input file}, when you want full output from
3847 included header files to be generated (and made globally visible).  The
3848 included header file, in turn, should use @samp{#pragma interface}.
3849 Backup copies of inline member functions, debugging information, and the
3850 internal tables used to implement virtual functions are all generated in
3851 implementation files.
3853 @cindex implied @code{#pragma implementation}
3854 @cindex @code{#pragma implementation}, implied
3855 @cindex naming convention, implementation headers
3856 If you use @samp{#pragma implementation} with no argument, it applies to
3857 an include file with the same basename@footnote{A file's @dfn{basename}
3858 was the name stripped of all leading path information and of trailing
3859 suffixes, such as @samp{.h} or @samp{.C} or @samp{.cc}.} as your source
3860 file.  For example, in @file{allclass.cc}, giving just
3861 @samp{#pragma implementation}
3862 by itself is equivalent to @samp{#pragma implementation "allclass.h"}.
3864 In versions of GNU C++ prior to 2.6.0 @file{allclass.h} was treated as
3865 an implementation file whenever you would include it from
3866 @file{allclass.cc} even if you never specified @samp{#pragma
3867 implementation}.  This was deemed to be more trouble than it was worth,
3868 however, and disabled.
3870 If you use an explicit @samp{#pragma implementation}, it must appear in
3871 your source file @emph{before} you include the affected header files.
3873 Use the string argument if you want a single implementation file to
3874 include code from multiple header files.  (You must also use
3875 @samp{#include} to include the header file; @samp{#pragma
3876 implementation} only specifies how to use the file---it doesn't actually
3877 include it.)
3879 There is no way to split up the contents of a single header file into
3880 multiple implementation files.
3881 @end table
3883 @cindex inlining and C++ pragmas
3884 @cindex C++ pragmas, effect on inlining
3885 @cindex pragmas in C++, effect on inlining
3886 @samp{#pragma implementation} and @samp{#pragma interface} also have an
3887 effect on function inlining.
3889 If you define a class in a header file marked with @samp{#pragma
3890 interface}, the effect on a function defined in that class is similar to
3891 an explicit @code{extern} declaration---the compiler emits no code at
3892 all to define an independent version of the function.  Its definition
3893 is used only for inlining with its callers.
3895 Conversely, when you include the same header file in a main source file
3896 that declares it as @samp{#pragma implementation}, the compiler emits
3897 code for the function itself; this defines a version of the function
3898 that can be found via pointers (or by callers compiled without
3899 inlining).  If all calls to the function can be inlined, you can avoid
3900 emitting the function by compiling with @samp{-fno-implement-inlines}.
3901 If any calls were not inlined, you will get linker errors.
3903 @node Template Instantiation
3904 @section Where's the Template?
3906 @cindex template instantiation
3908 C++ templates are the first language feature to require more
3909 intelligence from the environment than one usually finds on a UNIX
3910 system.  Somehow the compiler and linker have to make sure that each
3911 template instance occurs exactly once in the executable if it is needed,
3912 and not at all otherwise.  There are two basic approaches to this
3913 problem, which I will refer to as the Borland model and the Cfront model.
3915 @table @asis
3916 @item Borland model
3917 Borland C++ solved the template instantiation problem by adding the code
3918 equivalent of common blocks to their linker; the compiler emits template
3919 instances in each translation unit that uses them, and the linker
3920 collapses them together.  The advantage of this model is that the linker
3921 only has to consider the object files themselves; there is no external
3922 complexity to worry about.  This disadvantage is that compilation time
3923 is increased because the template code is being compiled repeatedly.
3924 Code written for this model tends to include definitions of all
3925 templates in the header file, since they must be seen to be
3926 instantiated.
3928 @item Cfront model
3929 The AT&T C++ translator, Cfront, solved the template instantiation
3930 problem by creating the notion of a template repository, an
3931 automatically maintained place where template instances are stored.  A
3932 more modern version of the repository works as follows: As individual
3933 object files are built, the compiler places any template definitions and
3934 instantiations encountered in the repository.  At link time, the link
3935 wrapper adds in the objects in the repository and compiles any needed
3936 instances that were not previously emitted.  The advantages of this
3937 model are more optimal compilation speed and the ability to use the
3938 system linker; to implement the Borland model a compiler vendor also
3939 needs to replace the linker.  The disadvantages are vastly increased
3940 complexity, and thus potential for error; for some code this can be
3941 just as transparent, but in practice it can been very difficult to build
3942 multiple programs in one directory and one program in multiple
3943 directories.  Code written for this model tends to separate definitions
3944 of non-inline member templates into a separate file, which should be
3945 compiled separately.
3946 @end table
3948 When used with GNU ld version 2.8 or later on an ELF system such as
3949 Linux/GNU or Solaris 2, or on Microsoft Windows, g++ supports the
3950 Borland model.  On other systems, g++ implements neither automatic
3951 model.
3953 A future version of g++ will support a hybrid model whereby the compiler
3954 will emit any instantiations for which the template definition is
3955 included in the compile, and store template definitions and
3956 instantiation context information into the object file for the rest.
3957 The link wrapper will extract that information as necessary and invoke
3958 the compiler to produce the remaining instantiations.  The linker will
3959 then combine duplicate instantiations.
3961 In the mean time, you have the following options for dealing with
3962 template instantiations:
3964 @enumerate
3965 @item
3966 Compile your template-using code with @samp{-frepo}.  The compiler will
3967 generate files with the extension @samp{.rpo} listing all of the
3968 template instantiations used in the corresponding object files which
3969 could be instantiated there; the link wrapper, @samp{collect2}, will
3970 then update the @samp{.rpo} files to tell the compiler where to place
3971 those instantiations and rebuild any affected object files.  The
3972 link-time overhead is negligible after the first pass, as the compiler
3973 will continue to place the instantiations in the same files.
3975 This is your best option for application code written for the Borland
3976 model, as it will just work.  Code written for the Cfront model will
3977 need to be modified so that the template definitions are available at
3978 one or more points of instantiation; usually this is as simple as adding
3979 @code{#include <tmethods.cc>} to the end of each template header.
3981 For library code, if you want the library to provide all of the template
3982 instantiations it needs, just try to link all of its object files
3983 together; the link will fail, but cause the instantiations to be
3984 generated as a side effect.  Be warned, however, that this may cause
3985 conflicts if multiple libraries try to provide the same instantiations.
3986 For greater control, use explicit instantiation as described in the next
3987 option.
3989 @item
3990 Compile your code with @samp{-fno-implicit-templates} to disable the
3991 implicit generation of template instances, and explicitly instantiate
3992 all the ones you use.  This approach requires more knowledge of exactly
3993 which instances you need than do the others, but it's less
3994 mysterious and allows greater control.  You can scatter the explicit
3995 instantiations throughout your program, perhaps putting them in the
3996 translation units where the instances are used or the translation units
3997 that define the templates themselves; you can put all of the explicit
3998 instantiations you need into one big file; or you can create small files
3999 like
4001 @example
4002 #include "Foo.h"
4003 #include "Foo.cc"
4005 template class Foo<int>;
4006 template ostream& operator <<
4007                 (ostream&, const Foo<int>&);
4008 @end example
4010 for each of the instances you need, and create a template instantiation
4011 library from those.
4013 If you are using Cfront-model code, you can probably get away with not
4014 using @samp{-fno-implicit-templates} when compiling files that don't
4015 @samp{#include} the member template definitions.
4017 If you use one big file to do the instantiations, you may want to
4018 compile it without @samp{-fno-implicit-templates} so you get all of the
4019 instances required by your explicit instantiations (but not by any
4020 other files) without having to specify them as well.
4022 g++ has extended the template instantiation syntax outlined in the
4023 Working Paper to allow forward declaration of explicit instantiations
4024 (with @code{extern}), instantiation of the compiler support data for a
4025 template class (i.e. the vtable) without instantiating any of its
4026 members (with @code{inline}), and instantiation of only the static data
4027 members of a template class, without the support data or member
4028 functions (with (@code{static}):
4030 @example
4031 extern template int max (int, int);
4032 inline template class Foo<int>;
4033 static template class Foo<int>;
4034 @end example
4036 @item
4037 Do nothing.  Pretend g++ does implement automatic instantiation
4038 management.  Code written for the Borland model will work fine, but
4039 each translation unit will contain instances of each of the templates it
4040 uses.  In a large program, this can lead to an unacceptable amount of code
4041 duplication.
4043 @item
4044 Add @samp{#pragma interface} to all files containing template
4045 definitions.  For each of these files, add @samp{#pragma implementation
4046 "@var{filename}"} to the top of some @samp{.C} file which
4047 @samp{#include}s it.  Then compile everything with
4048 @samp{-fexternal-templates}.  The templates will then only be expanded
4049 in the translation unit which implements them (i.e. has a @samp{#pragma
4050 implementation} line for the file where they live); all other files will
4051 use external references.  If you're lucky, everything should work
4052 properly.  If you get undefined symbol errors, you need to make sure
4053 that each template instance which is used in the program is used in the
4054 file which implements that template.  If you don't have any use for a
4055 particular instance in that file, you can just instantiate it
4056 explicitly, using the syntax from the latest C++ working paper:
4058 @example
4059 template class A<int>;
4060 template ostream& operator << (ostream&, const A<int>&);
4061 @end example
4063 This strategy will work with code written for either model.  If you are
4064 using code written for the Cfront model, the file containing a class
4065 template and the file containing its member templates should be
4066 implemented in the same translation unit.
4068 A slight variation on this approach is to instead use the flag
4069 @samp{-falt-external-templates}; this flag causes template
4070 instances to be emitted in the translation unit that implements the
4071 header where they are first instantiated, rather than the one which
4072 implements the file where the templates are defined.  This header must
4073 be the same in all translation units, or things are likely to break.
4075 @xref{C++ Interface,,Declarations and Definitions in One Header}, for
4076 more discussion of these pragmas.
4077 @end enumerate
4079 @node Bound member functions
4080 @section Extracting the function pointer from a bound pointer to member function
4082 @cindex pmf
4083 @cindex pointer to member function
4084 @cindex bound pointer to member function
4086 In C++, pointer to member functions (PMFs) are implemented using a wide
4087 pointer of sorts to handle all the possible call mechanisms; the PMF
4088 needs to store information about how to adjust the @samp{this} pointer,
4089 and if the function pointed to is virtual, where to find the vtable, and
4090 where in the vtable to look for the member function.  If you are using
4091 PMFs in an inner loop, you should really reconsider that decision.  If
4092 that is not an option, you can extract the pointer to the function that
4093 would be called for a given object/PMF pair and call it directly inside
4094 the inner loop, to save a bit of time.
4096 Note that you will still be paying the penalty for the call through a
4097 function pointer; on most modern architectures, such a call defeats the
4098 branch prediction features of the CPU.  This is also true of normal
4099 virtual function calls.
4101 The syntax for this extension is
4103 @example
4104 extern A a;
4105 extern int (A::*fp)();
4106 typedef int (*fptr)(A *);
4108 fptr p = (fptr)(a.*fp);
4109 @end example
4111 For PMF constants (i.e. expressions of the form @samp{&Klasse::Member}),
4112 no object is needed to obtain the address of the function. They can be
4113 converted to function pointers directly:
4115 @example
4116 fptr p1 = (fptr)(&A::foo);
4117 @end example
4119 You must specify @samp{-Wno-pmf-conversions} to use this extension.
4121 @node C++ Attributes
4122 @section C++-Specific Variable, Function, and Type Attributes
4124 Some attributes only make sense for C++ programs.
4126 @table @code
4127 @item init_priority (@var{priority})
4128 @cindex init_priority attribute
4131 In Standard C++, objects defined at namespace scope are guaranteed to be
4132 initialized in an order in strict accordance with that of their definitions
4133 @emph{in a given translation unit}.  No guarantee is made for initializations
4134 across translation units.  However, GNU C++ allows users to control the
4135 order of initialization of objects defined at namespace socpe with the
4136 @code{init_priority} attribute by specifying a relative @var{priority},
4137 a constant integral expression currently bounded between 101 and 65535
4138 inclusive.  Lower numbers indicate a higher priority.
4140 In the following example, @code{A} would normally be created before
4141 @code{B}, but the @code{init_priority} attribute has reversed that order:
4143 @example
4144 Some_Class  A  __attribute__ ((init_priority (2000)));
4145 Some_Class  B  __attribute__ ((init_priority (543)));
4146 @end example
4148 @noindent
4149 Note that the particular values of @var{priority} do not matter; only their
4150 relative ordering.
4153 @item com_interface
4154 @cindex com_interface attribute
4156 @c This is based on:  1) grepping the code, 
4157 @c 2) http://gcc.gnu.org/ml/gcc-bugs/1999-08n/msg01212.html
4158 @c 3) http://gcc.gnu.org/ml/gcc-bugs/1999-08n/msg01215.html
4159 @c and 4) a lot of guesswork.  You can tell I don't use COM.  -pme 21Dec00
4161 This type attribute takes no parameters, and marks a class or struct as an
4162 interface for communication via COM; the class will support the COM ABI
4163 rather than the full C++ ABI.  Currently this means that RTTI is not possible
4164 with the resulting class heirarchy.  The virtual pointer table will be
4165 changed to be COM-compliant.  Also, all classes and structs derived from one
4166 marked with this attribute are implicitly marked with the same attribute;
4167 thus, only the base class in a COM hierarchy needs @code{com_interface}.
4169 @end table
4171 @node Deprecated Features
4172 @section Deprecated Features
4174 In the past, the GNU C++ compiler was extended to experiment with new
4175 features, at a time when the C++ language was still evolving. Now that
4176 the C++ standard is complete, some of those features are superseded by
4177 superior alternatives. Using the old features might cause a warning in
4178 some cases that the feature will be dropped in the future. In other
4179 cases, the feature might be gone already.
4181 While the list below is not exhaustive, it documents some of the options
4182 that are now deprecated:
4184 @table @code
4185 @item -fexternal-templates
4186 @itemx -falt-external-templates
4187 These are two of the many ways for g++ to implement template
4188 instantiation. @xref{Template Instantiation}. The C++ standard clearly
4189 defines how template definitions have to be organized across
4190 implementation units. g++ has an implicit instantiation mechanism that
4191 should work just fine for standard-conforming code.
4193 @item -fstrict-prototype
4194 @itemx -fno-strict-prototype
4195 Previously it was possible to use an empty prototype parameter list to
4196 indicate an unspecified number of parameters (like C), rather than no
4197 parameters, as C++ demands. This feature has been removed, except where
4198 it is required for backwards compatibility @xref{Backwards Compatibility}.
4199 @end table
4201 The named return value extension has been deprecated, and will be
4202 removed from g++ at some point.
4204 @node Backwards Compatibility
4205 @section Backwards Compatibility
4206 @cindex Backwards Compatibility
4207 @cindex ARM [Annotated C++ Reference Manual]
4209 Now that there is a definitive ISO standard C++, g++ has a specification
4210 to adhere to. The C++ language evolved over time, and features that
4211 used to be acceptable in previous drafts of the standard, such as the ARM
4212 [Annotated C++ Reference Manual], are no longer accepted. In order to allow
4213 compilation of C++ written to such drafts, g++ contains some backwards
4214 compatibilities. @emph{All such backwards compatibility features are
4215 liable to disappear in future versions of g++.} They should be considered
4216 deprecated @xref{Deprecated Features}.
4218 @table @code
4219 @item For scope
4220 If a variable is declared at for scope, it used to remain in scope until
4221 the end of the scope which contained the for statement (rather than just
4222 within the for scope). g++ retains this, but issues a warning, if such a
4223 variable is accessed outside the for scope.
4225 @item implicit C language
4226 Old C system header files did not contain an @code{extern "C" @{...@}}
4227 scope to set the language. On such systems, all header files are
4228 implicitly scoped inside a C language scope. Also, an empty prototype
4229 @code{()} will be treated as an unspecified number of arguments, rather
4230 than no arguments, as C++ demands.
4231 @end table