source: trunk/third/gcc/extend.texi @ 11288

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