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