OSDN Git Service

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