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