Merge branch 'vendor/GCC47'
[dragonfly.git] / contrib / gcc-4.7 / gcc / doc / extend.texi
CommitLineData
e4b17023
JM
1@c Copyright (C) 1988, 1989, 1992, 1993, 1994, 1996, 1998, 1999, 2000, 2001,
2@c 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
3@c Free Software Foundation, Inc.
4
5@c This is part of the GCC manual.
6@c For copying conditions, see the file gcc.texi.
7
8@node C Extensions
9@chapter Extensions to the C Language Family
10@cindex extensions, C language
11@cindex C language extensions
12
13@opindex pedantic
14GNU C provides several language features not found in ISO standard C@.
15(The @option{-pedantic} option directs GCC to print a warning message if
16any of these features is used.) To test for the availability of these
17features in conditional compilation, check for a predefined macro
18@code{__GNUC__}, which is always defined under GCC@.
19
20These extensions are available in C and Objective-C@. Most of them are
21also available in C++. @xref{C++ Extensions,,Extensions to the
22C++ Language}, for extensions that apply @emph{only} to C++.
23
24Some features that are in ISO C99 but not C90 or C++ are also, as
25extensions, accepted by GCC in C90 mode and in C++.
26
27@menu
28* Statement Exprs:: Putting statements and declarations inside expressions.
29* Local Labels:: Labels local to a block.
30* Labels as Values:: Getting pointers to labels, and computed gotos.
31* Nested Functions:: As in Algol and Pascal, lexical scoping of functions.
32* Constructing Calls:: Dispatching a call to another function.
33* Typeof:: @code{typeof}: referring to the type of an expression.
34* Conditionals:: Omitting the middle operand of a @samp{?:} expression.
35* Long Long:: Double-word integers---@code{long long int}.
36* __int128:: 128-bit integers---@code{__int128}.
37* Complex:: Data types for complex numbers.
38* Floating Types:: Additional Floating Types.
39* Half-Precision:: Half-Precision Floating Point.
40* Decimal Float:: Decimal Floating Types.
41* Hex Floats:: Hexadecimal floating-point constants.
42* Fixed-Point:: Fixed-Point Types.
43* Named Address Spaces::Named address spaces.
44* Zero Length:: Zero-length arrays.
45* Variable Length:: Arrays whose length is computed at run time.
46* Empty Structures:: Structures with no members.
47* Variadic Macros:: Macros with a variable number of arguments.
48* Escaped Newlines:: Slightly looser rules for escaped newlines.
49* Subscripting:: Any array can be subscripted, even if not an lvalue.
50* Pointer Arith:: Arithmetic on @code{void}-pointers and function pointers.
51* Initializers:: Non-constant initializers.
52* Compound Literals:: Compound literals give structures, unions
53 or arrays as values.
54* Designated Inits:: Labeling elements of initializers.
55* Cast to Union:: Casting to union type from any member of the union.
56* Case Ranges:: `case 1 ... 9' and such.
57* Mixed Declarations:: Mixing declarations and code.
58* Function Attributes:: Declaring that functions have no side effects,
59 or that they can never return.
60* Attribute Syntax:: Formal syntax for attributes.
61* Function Prototypes:: Prototype declarations and old-style definitions.
62* C++ Comments:: C++ comments are recognized.
63* Dollar Signs:: Dollar sign is allowed in identifiers.
64* Character Escapes:: @samp{\e} stands for the character @key{ESC}.
65* Variable Attributes:: Specifying attributes of variables.
66* Type Attributes:: Specifying attributes of types.
67* Alignment:: Inquiring about the alignment of a type or variable.
68* Inline:: Defining inline functions (as fast as macros).
69* Volatiles:: What constitutes an access to a volatile object.
70* Extended Asm:: Assembler instructions with C expressions as operands.
71 (With them you can define ``built-in'' functions.)
72* Constraints:: Constraints for asm operands
73* Asm Labels:: Specifying the assembler name to use for a C symbol.
74* Explicit Reg Vars:: Defining variables residing in specified registers.
75* Alternate Keywords:: @code{__const__}, @code{__asm__}, etc., for header files.
76* Incomplete Enums:: @code{enum foo;}, with details to follow.
77* Function Names:: Printable strings which are the name of the current
78 function.
79* Return Address:: Getting the return or frame address of a function.
80* Vector Extensions:: Using vector instructions through built-in functions.
81* Offsetof:: Special syntax for implementing @code{offsetof}.
82* __sync Builtins:: Legacy built-in functions for atomic memory access.
83* __atomic Builtins:: Atomic built-in functions with memory model.
84* Object Size Checking:: Built-in functions for limited buffer overflow
85 checking.
86* Other Builtins:: Other built-in functions.
87* Target Builtins:: Built-in functions specific to particular targets.
88* Target Format Checks:: Format checks specific to particular targets.
89* Pragmas:: Pragmas accepted by GCC.
90* Unnamed Fields:: Unnamed struct/union fields within structs/unions.
91* Thread-Local:: Per-thread variables.
92* Binary constants:: Binary constants using the @samp{0b} prefix.
93@end menu
94
95@node Statement Exprs
96@section Statements and Declarations in Expressions
97@cindex statements inside expressions
98@cindex declarations inside expressions
99@cindex expressions containing statements
100@cindex macros, statements in expressions
101
102@c the above section title wrapped and causes an underfull hbox.. i
103@c changed it from "within" to "in". --mew 4feb93
104A compound statement enclosed in parentheses may appear as an expression
105in GNU C@. This allows you to use loops, switches, and local variables
106within an expression.
107
108Recall that a compound statement is a sequence of statements surrounded
109by braces; in this construct, parentheses go around the braces. For
110example:
111
112@smallexample
113(@{ int y = foo (); int z;
114 if (y > 0) z = y;
115 else z = - y;
116 z; @})
117@end smallexample
118
119@noindent
120is a valid (though slightly more complex than necessary) expression
121for the absolute value of @code{foo ()}.
122
123The last thing in the compound statement should be an expression
124followed by a semicolon; the value of this subexpression serves as the
125value of the entire construct. (If you use some other kind of statement
126last within the braces, the construct has type @code{void}, and thus
127effectively no value.)
128
129This feature is especially useful in making macro definitions ``safe'' (so
130that they evaluate each operand exactly once). For example, the
131``maximum'' function is commonly defined as a macro in standard C as
132follows:
133
134@smallexample
135#define max(a,b) ((a) > (b) ? (a) : (b))
136@end smallexample
137
138@noindent
139@cindex side effects, macro argument
140But this definition computes either @var{a} or @var{b} twice, with bad
141results if the operand has side effects. In GNU C, if you know the
142type of the operands (here taken as @code{int}), you can define
143the macro safely as follows:
144
145@smallexample
146#define maxint(a,b) \
147 (@{int _a = (a), _b = (b); _a > _b ? _a : _b; @})
148@end smallexample
149
150Embedded statements are not allowed in constant expressions, such as
151the value of an enumeration constant, the width of a bit-field, or
152the initial value of a static variable.
153
154If you don't know the type of the operand, you can still do this, but you
155must use @code{typeof} (@pxref{Typeof}).
156
157In G++, the result value of a statement expression undergoes array and
158function pointer decay, and is returned by value to the enclosing
159expression. For instance, if @code{A} is a class, then
160
161@smallexample
162 A a;
163
164 (@{a;@}).Foo ()
165@end smallexample
166
167@noindent
168will construct a temporary @code{A} object to hold the result of the
169statement expression, and that will be used to invoke @code{Foo}.
170Therefore the @code{this} pointer observed by @code{Foo} will not be the
171address of @code{a}.
172
173Any temporaries created within a statement within a statement expression
174will be destroyed at the statement's end. This makes statement
175expressions inside macros slightly different from function calls. In
176the latter case temporaries introduced during argument evaluation will
177be destroyed at the end of the statement that includes the function
178call. In the statement expression case they will be destroyed during
179the statement expression. For instance,
180
181@smallexample
182#define macro(a) (@{__typeof__(a) b = (a); b + 3; @})
183template<typename T> T function(T a) @{ T b = a; return b + 3; @}
184
185void foo ()
186@{
187 macro (X ());
188 function (X ());
189@}
190@end smallexample
191
192@noindent
193will have different places where temporaries are destroyed. For the
194@code{macro} case, the temporary @code{X} will be destroyed just after
195the initialization of @code{b}. In the @code{function} case that
196temporary will be destroyed when the function returns.
197
198These considerations mean that it is probably a bad idea to use
199statement-expressions of this form in header files that are designed to
200work with C++. (Note that some versions of the GNU C Library contained
201header files using statement-expression that lead to precisely this
202bug.)
203
204Jumping into a statement expression with @code{goto} or using a
205@code{switch} statement outside the statement expression with a
206@code{case} or @code{default} label inside the statement expression is
207not permitted. Jumping into a statement expression with a computed
208@code{goto} (@pxref{Labels as Values}) yields undefined behavior.
209Jumping out of a statement expression is permitted, but if the
210statement expression is part of a larger expression then it is
211unspecified which other subexpressions of that expression have been
212evaluated except where the language definition requires certain
213subexpressions to be evaluated before or after the statement
214expression. In any case, as with a function call the evaluation of a
215statement expression is not interleaved with the evaluation of other
216parts of the containing expression. For example,
217
218@smallexample
219 foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
220@end smallexample
221
222@noindent
223will call @code{foo} and @code{bar1} and will not call @code{baz} but
224may or may not call @code{bar2}. If @code{bar2} is called, it will be
225called after @code{foo} and before @code{bar1}
226
227@node Local Labels
228@section Locally Declared Labels
229@cindex local labels
230@cindex macros, local labels
231
232GCC allows you to declare @dfn{local labels} in any nested block
233scope. A local label is just like an ordinary label, but you can
234only reference it (with a @code{goto} statement, or by taking its
235address) within the block in which it was declared.
236
237A local label declaration looks like this:
238
239@smallexample
240__label__ @var{label};
241@end smallexample
242
243@noindent
244or
245
246@smallexample
247__label__ @var{label1}, @var{label2}, /* @r{@dots{}} */;
248@end smallexample
249
250Local label declarations must come at the beginning of the block,
251before any ordinary declarations or statements.
252
253The label declaration defines the label @emph{name}, but does not define
254the label itself. You must do this in the usual way, with
255@code{@var{label}:}, within the statements of the statement expression.
256
257The local label feature is useful for complex macros. If a macro
258contains nested loops, a @code{goto} can be useful for breaking out of
259them. However, an ordinary label whose scope is the whole function
260cannot be used: if the macro can be expanded several times in one
261function, the label will be multiply defined in that function. A
262local label avoids this problem. For example:
263
264@smallexample
265#define SEARCH(value, array, target) \
266do @{ \
267 __label__ found; \
268 typeof (target) _SEARCH_target = (target); \
269 typeof (*(array)) *_SEARCH_array = (array); \
270 int i, j; \
271 int value; \
272 for (i = 0; i < max; i++) \
273 for (j = 0; j < max; j++) \
274 if (_SEARCH_array[i][j] == _SEARCH_target) \
275 @{ (value) = i; goto found; @} \
276 (value) = -1; \
277 found:; \
278@} while (0)
279@end smallexample
280
281This could also be written using a statement-expression:
282
283@smallexample
284#define SEARCH(array, target) \
285(@{ \
286 __label__ found; \
287 typeof (target) _SEARCH_target = (target); \
288 typeof (*(array)) *_SEARCH_array = (array); \
289 int i, j; \
290 int value; \
291 for (i = 0; i < max; i++) \
292 for (j = 0; j < max; j++) \
293 if (_SEARCH_array[i][j] == _SEARCH_target) \
294 @{ value = i; goto found; @} \
295 value = -1; \
296 found: \
297 value; \
298@})
299@end smallexample
300
301Local label declarations also make the labels they declare visible to
302nested functions, if there are any. @xref{Nested Functions}, for details.
303
304@node Labels as Values
305@section Labels as Values
306@cindex labels as values
307@cindex computed gotos
308@cindex goto with computed label
309@cindex address of a label
310
311You can get the address of a label defined in the current function
312(or a containing function) with the unary operator @samp{&&}. The
313value has type @code{void *}. This value is a constant and can be used
314wherever a constant of that type is valid. For example:
315
316@smallexample
317void *ptr;
318/* @r{@dots{}} */
319ptr = &&foo;
320@end smallexample
321
322To use these values, you need to be able to jump to one. This is done
323with the computed goto statement@footnote{The analogous feature in
324Fortran is called an assigned goto, but that name seems inappropriate in
325C, where one can do more than simply store label addresses in label
326variables.}, @code{goto *@var{exp};}. For example,
327
328@smallexample
329goto *ptr;
330@end smallexample
331
332@noindent
333Any expression of type @code{void *} is allowed.
334
335One way of using these constants is in initializing a static array that
336will serve as a jump table:
337
338@smallexample
339static void *array[] = @{ &&foo, &&bar, &&hack @};
340@end smallexample
341
342Then you can select a label with indexing, like this:
343
344@smallexample
345goto *array[i];
346@end smallexample
347
348@noindent
349Note that this does not check whether the subscript is in bounds---array
350indexing in C never does that.
351
352Such an array of label values serves a purpose much like that of the
353@code{switch} statement. The @code{switch} statement is cleaner, so
354use that rather than an array unless the problem does not fit a
355@code{switch} statement very well.
356
357Another use of label values is in an interpreter for threaded code.
358The labels within the interpreter function can be stored in the
359threaded code for super-fast dispatching.
360
361You may not use this mechanism to jump to code in a different function.
362If you do that, totally unpredictable things will happen. The best way to
363avoid this is to store the label address only in automatic variables and
364never pass it as an argument.
365
366An alternate way to write the above example is
367
368@smallexample
369static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
370 &&hack - &&foo @};
371goto *(&&foo + array[i]);
372@end smallexample
373
374@noindent
375This is more friendly to code living in shared libraries, as it reduces
376the number of dynamic relocations that are needed, and by consequence,
377allows the data to be read-only.
95d28233
JM
378This alternative with label differences is not supported for the AVR target,
379please use the first approach for AVR programs.
e4b17023
JM
380
381The @code{&&foo} expressions for the same label might have different
382values if the containing function is inlined or cloned. If a program
383relies on them being always the same,
384@code{__attribute__((__noinline__,__noclone__))} should be used to
385prevent inlining and cloning. If @code{&&foo} is used in a static
386variable initializer, inlining and cloning is forbidden.
387
388@node Nested Functions
389@section Nested Functions
390@cindex nested functions
391@cindex downward funargs
392@cindex thunks
393
394A @dfn{nested function} is a function defined inside another function.
395(Nested functions are not supported for GNU C++.) The nested function's
396name is local to the block where it is defined. For example, here we
397define a nested function named @code{square}, and call it twice:
398
399@smallexample
400@group
401foo (double a, double b)
402@{
403 double square (double z) @{ return z * z; @}
404
405 return square (a) + square (b);
406@}
407@end group
408@end smallexample
409
410The nested function can access all the variables of the containing
411function that are visible at the point of its definition. This is
412called @dfn{lexical scoping}. For example, here we show a nested
413function which uses an inherited variable named @code{offset}:
414
415@smallexample
416@group
417bar (int *array, int offset, int size)
418@{
419 int access (int *array, int index)
420 @{ return array[index + offset]; @}
421 int i;
422 /* @r{@dots{}} */
423 for (i = 0; i < size; i++)
424 /* @r{@dots{}} */ access (array, i) /* @r{@dots{}} */
425@}
426@end group
427@end smallexample
428
429Nested function definitions are permitted within functions in the places
430where variable definitions are allowed; that is, in any block, mixed
431with the other declarations and statements in the block.
432
433It is possible to call the nested function from outside the scope of its
434name by storing its address or passing the address to another function:
435
436@smallexample
437hack (int *array, int size)
438@{
439 void store (int index, int value)
440 @{ array[index] = value; @}
441
442 intermediate (store, size);
443@}
444@end smallexample
445
446Here, the function @code{intermediate} receives the address of
447@code{store} as an argument. If @code{intermediate} calls @code{store},
448the arguments given to @code{store} are used to store into @code{array}.
449But this technique works only so long as the containing function
450(@code{hack}, in this example) does not exit.
451
452If you try to call the nested function through its address after the
453containing function has exited, all hell will break loose. If you try
454to call it after a containing scope level has exited, and if it refers
455to some of the variables that are no longer in scope, you may be lucky,
456but it's not wise to take the risk. If, however, the nested function
457does not refer to anything that has gone out of scope, you should be
458safe.
459
460GCC implements taking the address of a nested function using a technique
461called @dfn{trampolines}. This technique was described in
462@cite{Lexical Closures for C++} (Thomas M. Breuel, USENIX
463C++ Conference Proceedings, October 17-21, 1988).
464
465A nested function can jump to a label inherited from a containing
466function, provided the label was explicitly declared in the containing
467function (@pxref{Local Labels}). Such a jump returns instantly to the
468containing function, exiting the nested function which did the
469@code{goto} and any intermediate functions as well. Here is an example:
470
471@smallexample
472@group
473bar (int *array, int offset, int size)
474@{
475 __label__ failure;
476 int access (int *array, int index)
477 @{
478 if (index > size)
479 goto failure;
480 return array[index + offset];
481 @}
482 int i;
483 /* @r{@dots{}} */
484 for (i = 0; i < size; i++)
485 /* @r{@dots{}} */ access (array, i) /* @r{@dots{}} */
486 /* @r{@dots{}} */
487 return 0;
488
489 /* @r{Control comes here from @code{access}
490 if it detects an error.} */
491 failure:
492 return -1;
493@}
494@end group
495@end smallexample
496
497A nested function always has no linkage. Declaring one with
498@code{extern} or @code{static} is erroneous. If you need to declare the nested function
499before its definition, use @code{auto} (which is otherwise meaningless
500for function declarations).
501
502@smallexample
503bar (int *array, int offset, int size)
504@{
505 __label__ failure;
506 auto int access (int *, int);
507 /* @r{@dots{}} */
508 int access (int *array, int index)
509 @{
510 if (index > size)
511 goto failure;
512 return array[index + offset];
513 @}
514 /* @r{@dots{}} */
515@}
516@end smallexample
517
518@node Constructing Calls
519@section Constructing Function Calls
520@cindex constructing calls
521@cindex forwarding calls
522
523Using the built-in functions described below, you can record
524the arguments a function received, and call another function
525with the same arguments, without knowing the number or types
526of the arguments.
527
528You can also record the return value of that function call,
529and later return that value, without knowing what data type
530the function tried to return (as long as your caller expects
531that data type).
532
533However, these built-in functions may interact badly with some
534sophisticated features or other extensions of the language. It
535is, therefore, not recommended to use them outside very simple
536functions acting as mere forwarders for their arguments.
537
538@deftypefn {Built-in Function} {void *} __builtin_apply_args ()
539This built-in function returns a pointer to data
540describing how to perform a call with the same arguments as were passed
541to the current function.
542
543The function saves the arg pointer register, structure value address,
544and all registers that might be used to pass arguments to a function
545into a block of memory allocated on the stack. Then it returns the
546address of that block.
547@end deftypefn
548
549@deftypefn {Built-in Function} {void *} __builtin_apply (void (*@var{function})(), void *@var{arguments}, size_t @var{size})
550This built-in function invokes @var{function}
551with a copy of the parameters described by @var{arguments}
552and @var{size}.
553
554The value of @var{arguments} should be the value returned by
555@code{__builtin_apply_args}. The argument @var{size} specifies the size
556of the stack argument data, in bytes.
557
558This function returns a pointer to data describing
559how to return whatever value was returned by @var{function}. The data
560is saved in a block of memory allocated on the stack.
561
562It is not always simple to compute the proper value for @var{size}. The
563value is used by @code{__builtin_apply} to compute the amount of data
564that should be pushed on the stack and copied from the incoming argument
565area.
566@end deftypefn
567
568@deftypefn {Built-in Function} {void} __builtin_return (void *@var{result})
569This built-in function returns the value described by @var{result} from
570the containing function. You should specify, for @var{result}, a value
571returned by @code{__builtin_apply}.
572@end deftypefn
573
574@deftypefn {Built-in Function} {} __builtin_va_arg_pack ()
575This built-in function represents all anonymous arguments of an inline
576function. It can be used only in inline functions which will be always
577inlined, never compiled as a separate function, such as those using
578@code{__attribute__ ((__always_inline__))} or
579@code{__attribute__ ((__gnu_inline__))} extern inline functions.
580It must be only passed as last argument to some other function
581with variable arguments. This is useful for writing small wrapper
582inlines for variable argument functions, when using preprocessor
583macros is undesirable. For example:
584@smallexample
585extern int myprintf (FILE *f, const char *format, ...);
586extern inline __attribute__ ((__gnu_inline__)) int
587myprintf (FILE *f, const char *format, ...)
588@{
589 int r = fprintf (f, "myprintf: ");
590 if (r < 0)
591 return r;
592 int s = fprintf (f, format, __builtin_va_arg_pack ());
593 if (s < 0)
594 return s;
595 return r + s;
596@}
597@end smallexample
598@end deftypefn
599
600@deftypefn {Built-in Function} {size_t} __builtin_va_arg_pack_len ()
601This built-in function returns the number of anonymous arguments of
602an inline function. It can be used only in inline functions which
603will be always inlined, never compiled as a separate function, such
604as those using @code{__attribute__ ((__always_inline__))} or
605@code{__attribute__ ((__gnu_inline__))} extern inline functions.
606For example following will do link or runtime checking of open
607arguments for optimized code:
608@smallexample
609#ifdef __OPTIMIZE__
610extern inline __attribute__((__gnu_inline__)) int
611myopen (const char *path, int oflag, ...)
612@{
613 if (__builtin_va_arg_pack_len () > 1)
614 warn_open_too_many_arguments ();
615
616 if (__builtin_constant_p (oflag))
617 @{
618 if ((oflag & O_CREAT) != 0 && __builtin_va_arg_pack_len () < 1)
619 @{
620 warn_open_missing_mode ();
621 return __open_2 (path, oflag);
622 @}
623 return open (path, oflag, __builtin_va_arg_pack ());
624 @}
625
626 if (__builtin_va_arg_pack_len () < 1)
627 return __open_2 (path, oflag);
628
629 return open (path, oflag, __builtin_va_arg_pack ());
630@}
631#endif
632@end smallexample
633@end deftypefn
634
635@node Typeof
636@section Referring to a Type with @code{typeof}
637@findex typeof
638@findex sizeof
639@cindex macros, types of arguments
640
641Another way to refer to the type of an expression is with @code{typeof}.
642The syntax of using of this keyword looks like @code{sizeof}, but the
643construct acts semantically like a type name defined with @code{typedef}.
644
645There are two ways of writing the argument to @code{typeof}: with an
646expression or with a type. Here is an example with an expression:
647
648@smallexample
649typeof (x[0](1))
650@end smallexample
651
652@noindent
653This assumes that @code{x} is an array of pointers to functions;
654the type described is that of the values of the functions.
655
656Here is an example with a typename as the argument:
657
658@smallexample
659typeof (int *)
660@end smallexample
661
662@noindent
663Here the type described is that of pointers to @code{int}.
664
665If you are writing a header file that must work when included in ISO C
666programs, write @code{__typeof__} instead of @code{typeof}.
667@xref{Alternate Keywords}.
668
669A @code{typeof}-construct can be used anywhere a typedef name could be
670used. For example, you can use it in a declaration, in a cast, or inside
671of @code{sizeof} or @code{typeof}.
672
673The operand of @code{typeof} is evaluated for its side effects if and
674only if it is an expression of variably modified type or the name of
675such a type.
676
677@code{typeof} is often useful in conjunction with the
678statements-within-expressions feature. Here is how the two together can
679be used to define a safe ``maximum'' macro that operates on any
680arithmetic type and evaluates each of its arguments exactly once:
681
682@smallexample
683#define max(a,b) \
684 (@{ typeof (a) _a = (a); \
685 typeof (b) _b = (b); \
686 _a > _b ? _a : _b; @})
687@end smallexample
688
689@cindex underscores in variables in macros
690@cindex @samp{_} in variables in macros
691@cindex local variables in macros
692@cindex variables, local, in macros
693@cindex macros, local variables in
694
695The reason for using names that start with underscores for the local
696variables is to avoid conflicts with variable names that occur within the
697expressions that are substituted for @code{a} and @code{b}. Eventually we
698hope to design a new form of declaration syntax that allows you to declare
699variables whose scopes start only after their initializers; this will be a
700more reliable way to prevent such conflicts.
701
702@noindent
703Some more examples of the use of @code{typeof}:
704
705@itemize @bullet
706@item
707This declares @code{y} with the type of what @code{x} points to.
708
709@smallexample
710typeof (*x) y;
711@end smallexample
712
713@item
714This declares @code{y} as an array of such values.
715
716@smallexample
717typeof (*x) y[4];
718@end smallexample
719
720@item
721This declares @code{y} as an array of pointers to characters:
722
723@smallexample
724typeof (typeof (char *)[4]) y;
725@end smallexample
726
727@noindent
728It is equivalent to the following traditional C declaration:
729
730@smallexample
731char *y[4];
732@end smallexample
733
734To see the meaning of the declaration using @code{typeof}, and why it
735might be a useful way to write, rewrite it with these macros:
736
737@smallexample
738#define pointer(T) typeof(T *)
739#define array(T, N) typeof(T [N])
740@end smallexample
741
742@noindent
743Now the declaration can be rewritten this way:
744
745@smallexample
746array (pointer (char), 4) y;
747@end smallexample
748
749@noindent
750Thus, @code{array (pointer (char), 4)} is the type of arrays of 4
751pointers to @code{char}.
752@end itemize
753
754@emph{Compatibility Note:} In addition to @code{typeof}, GCC 2 supported
755a more limited extension which permitted one to write
756
757@smallexample
758typedef @var{T} = @var{expr};
759@end smallexample
760
761@noindent
762with the effect of declaring @var{T} to have the type of the expression
763@var{expr}. This extension does not work with GCC 3 (versions between
7643.0 and 3.2 will crash; 3.2.1 and later give an error). Code which
765relies on it should be rewritten to use @code{typeof}:
766
767@smallexample
768typedef typeof(@var{expr}) @var{T};
769@end smallexample
770
771@noindent
772This will work with all versions of GCC@.
773
774@node Conditionals
775@section Conditionals with Omitted Operands
776@cindex conditional expressions, extensions
777@cindex omitted middle-operands
778@cindex middle-operands, omitted
779@cindex extensions, @code{?:}
780@cindex @code{?:} extensions
781
782The middle operand in a conditional expression may be omitted. Then
783if the first operand is nonzero, its value is the value of the conditional
784expression.
785
786Therefore, the expression
787
788@smallexample
789x ? : y
790@end smallexample
791
792@noindent
793has the value of @code{x} if that is nonzero; otherwise, the value of
794@code{y}.
795
796This example is perfectly equivalent to
797
798@smallexample
799x ? x : y
800@end smallexample
801
802@cindex side effect in @code{?:}
803@cindex @code{?:} side effect
804@noindent
805In this simple case, the ability to omit the middle operand is not
806especially useful. When it becomes useful is when the first operand does,
807or may (if it is a macro argument), contain a side effect. Then repeating
808the operand in the middle would perform the side effect twice. Omitting
809the middle operand uses the value already computed without the undesirable
810effects of recomputing it.
811
812@node __int128
813@section 128-bits integers
814@cindex @code{__int128} data types
815
816As an extension the integer scalar type @code{__int128} is supported for
817targets having an integer mode wide enough to hold 128-bit.
818Simply write @code{__int128} for a signed 128-bit integer, or
819@code{unsigned __int128} for an unsigned 128-bit integer. There is no
820support in GCC to express an integer constant of type @code{__int128}
821for targets having @code{long long} integer with less then 128 bit width.
822
823@node Long Long
824@section Double-Word Integers
825@cindex @code{long long} data types
826@cindex double-word arithmetic
827@cindex multiprecision arithmetic
828@cindex @code{LL} integer suffix
829@cindex @code{ULL} integer suffix
830
831ISO C99 supports data types for integers that are at least 64 bits wide,
832and as an extension GCC supports them in C90 mode and in C++.
833Simply write @code{long long int} for a signed integer, or
834@code{unsigned long long int} for an unsigned integer. To make an
835integer constant of type @code{long long int}, add the suffix @samp{LL}
836to the integer. To make an integer constant of type @code{unsigned long
837long int}, add the suffix @samp{ULL} to the integer.
838
839You can use these types in arithmetic like any other integer types.
840Addition, subtraction, and bitwise boolean operations on these types
841are open-coded on all types of machines. Multiplication is open-coded
842if the machine supports fullword-to-doubleword a widening multiply
843instruction. Division and shifts are open-coded only on machines that
844provide special support. The operations that are not open-coded use
845special library routines that come with GCC@.
846
847There may be pitfalls when you use @code{long long} types for function
848arguments, unless you declare function prototypes. If a function
849expects type @code{int} for its argument, and you pass a value of type
850@code{long long int}, confusion will result because the caller and the
851subroutine will disagree about the number of bytes for the argument.
852Likewise, if the function expects @code{long long int} and you pass
853@code{int}. The best way to avoid such problems is to use prototypes.
854
855@node Complex
856@section Complex Numbers
857@cindex complex numbers
858@cindex @code{_Complex} keyword
859@cindex @code{__complex__} keyword
860
861ISO C99 supports complex floating data types, and as an extension GCC
862supports them in C90 mode and in C++, and supports complex integer data
863types which are not part of ISO C99. You can declare complex types
864using the keyword @code{_Complex}. As an extension, the older GNU
865keyword @code{__complex__} is also supported.
866
867For example, @samp{_Complex double x;} declares @code{x} as a
868variable whose real part and imaginary part are both of type
869@code{double}. @samp{_Complex short int y;} declares @code{y} to
870have real and imaginary parts of type @code{short int}; this is not
871likely to be useful, but it shows that the set of complex types is
872complete.
873
874To write a constant with a complex data type, use the suffix @samp{i} or
875@samp{j} (either one; they are equivalent). For example, @code{2.5fi}
876has type @code{_Complex float} and @code{3i} has type
877@code{_Complex int}. Such a constant always has a pure imaginary
878value, but you can form any complex value you like by adding one to a
879real constant. This is a GNU extension; if you have an ISO C99
880conforming C library (such as GNU libc), and want to construct complex
881constants of floating type, you should include @code{<complex.h>} and
882use the macros @code{I} or @code{_Complex_I} instead.
883
884@cindex @code{__real__} keyword
885@cindex @code{__imag__} keyword
886To extract the real part of a complex-valued expression @var{exp}, write
887@code{__real__ @var{exp}}. Likewise, use @code{__imag__} to
888extract the imaginary part. This is a GNU extension; for values of
889floating type, you should use the ISO C99 functions @code{crealf},
890@code{creal}, @code{creall}, @code{cimagf}, @code{cimag} and
891@code{cimagl}, declared in @code{<complex.h>} and also provided as
892built-in functions by GCC@.
893
894@cindex complex conjugation
895The operator @samp{~} performs complex conjugation when used on a value
896with a complex type. This is a GNU extension; for values of
897floating type, you should use the ISO C99 functions @code{conjf},
898@code{conj} and @code{conjl}, declared in @code{<complex.h>} and also
899provided as built-in functions by GCC@.
900
901GCC can allocate complex automatic variables in a noncontiguous
902fashion; it's even possible for the real part to be in a register while
903the imaginary part is on the stack (or vice-versa). Only the DWARF2
904debug info format can represent this, so use of DWARF2 is recommended.
905If you are using the stabs debug info format, GCC describes a noncontiguous
906complex variable as if it were two separate variables of noncomplex type.
907If the variable's actual name is @code{foo}, the two fictitious
908variables are named @code{foo$real} and @code{foo$imag}. You can
909examine and set these two fictitious variables with your debugger.
910
911@node Floating Types
912@section Additional Floating Types
913@cindex additional floating types
914@cindex @code{__float80} data type
915@cindex @code{__float128} data type
916@cindex @code{w} floating point suffix
917@cindex @code{q} floating point suffix
918@cindex @code{W} floating point suffix
919@cindex @code{Q} floating point suffix
920
921As an extension, the GNU C compiler supports additional floating
922types, @code{__float80} and @code{__float128} to support 80bit
923(@code{XFmode}) and 128 bit (@code{TFmode}) floating types.
924Support for additional types includes the arithmetic operators:
925add, subtract, multiply, divide; unary arithmetic operators;
926relational operators; equality operators; and conversions to and from
927integer and other floating types. Use a suffix @samp{w} or @samp{W}
928in a literal constant of type @code{__float80} and @samp{q} or @samp{Q}
929for @code{_float128}. You can declare complex types using the
930corresponding internal complex type, @code{XCmode} for @code{__float80}
931type and @code{TCmode} for @code{__float128} type:
932
933@smallexample
934typedef _Complex float __attribute__((mode(TC))) _Complex128;
935typedef _Complex float __attribute__((mode(XC))) _Complex80;
936@end smallexample
937
938Not all targets support additional floating point types. @code{__float80}
939and @code{__float128} types are supported on i386, x86_64 and ia64 targets.
940The @code{__float128} type is supported on hppa HP-UX targets.
941
942@node Half-Precision
943@section Half-Precision Floating Point
944@cindex half-precision floating point
945@cindex @code{__fp16} data type
946
947On ARM targets, GCC supports half-precision (16-bit) floating point via
948the @code{__fp16} type. You must enable this type explicitly
949with the @option{-mfp16-format} command-line option in order to use it.
950
951ARM supports two incompatible representations for half-precision
952floating-point values. You must choose one of the representations and
953use it consistently in your program.
954
955Specifying @option{-mfp16-format=ieee} selects the IEEE 754-2008 format.
956This format can represent normalized values in the range of @math{2^{-14}} to 65504.
957There are 11 bits of significand precision, approximately 3
958decimal digits.
959
960Specifying @option{-mfp16-format=alternative} selects the ARM
961alternative format. This representation is similar to the IEEE
962format, but does not support infinities or NaNs. Instead, the range
963of exponents is extended, so that this format can represent normalized
964values in the range of @math{2^{-14}} to 131008.
965
966The @code{__fp16} type is a storage format only. For purposes
967of arithmetic and other operations, @code{__fp16} values in C or C++
968expressions are automatically promoted to @code{float}. In addition,
969you cannot declare a function with a return value or parameters
970of type @code{__fp16}.
971
972Note that conversions from @code{double} to @code{__fp16}
973involve an intermediate conversion to @code{float}. Because
974of rounding, this can sometimes produce a different result than a
975direct conversion.
976
977ARM provides hardware support for conversions between
978@code{__fp16} and @code{float} values
979as an extension to VFP and NEON (Advanced SIMD). GCC generates
980code using these hardware instructions if you compile with
981options to select an FPU that provides them;
982for example, @option{-mfpu=neon-fp16 -mfloat-abi=softfp},
983in addition to the @option{-mfp16-format} option to select
984a half-precision format.
985
986Language-level support for the @code{__fp16} data type is
987independent of whether GCC generates code using hardware floating-point
988instructions. In cases where hardware support is not specified, GCC
989implements conversions between @code{__fp16} and @code{float} values
990as library calls.
991
992@node Decimal Float
993@section Decimal Floating Types
994@cindex decimal floating types
995@cindex @code{_Decimal32} data type
996@cindex @code{_Decimal64} data type
997@cindex @code{_Decimal128} data type
998@cindex @code{df} integer suffix
999@cindex @code{dd} integer suffix
1000@cindex @code{dl} integer suffix
1001@cindex @code{DF} integer suffix
1002@cindex @code{DD} integer suffix
1003@cindex @code{DL} integer suffix
1004
1005As an extension, the GNU C compiler supports decimal floating types as
1006defined in the N1312 draft of ISO/IEC WDTR24732. Support for decimal
1007floating types in GCC will evolve as the draft technical report changes.
1008Calling conventions for any target might also change. Not all targets
1009support decimal floating types.
1010
1011The decimal floating types are @code{_Decimal32}, @code{_Decimal64}, and
1012@code{_Decimal128}. They use a radix of ten, unlike the floating types
1013@code{float}, @code{double}, and @code{long double} whose radix is not
1014specified by the C standard but is usually two.
1015
1016Support for decimal floating types includes the arithmetic operators
1017add, subtract, multiply, divide; unary arithmetic operators;
1018relational operators; equality operators; and conversions to and from
1019integer and other floating types. Use a suffix @samp{df} or
1020@samp{DF} in a literal constant of type @code{_Decimal32}, @samp{dd}
1021or @samp{DD} for @code{_Decimal64}, and @samp{dl} or @samp{DL} for
1022@code{_Decimal128}.
1023
1024GCC support of decimal float as specified by the draft technical report
1025is incomplete:
1026
1027@itemize @bullet
1028@item
1029When the value of a decimal floating type cannot be represented in the
1030integer type to which it is being converted, the result is undefined
1031rather than the result value specified by the draft technical report.
1032
1033@item
1034GCC does not provide the C library functionality associated with
1035@file{math.h}, @file{fenv.h}, @file{stdio.h}, @file{stdlib.h}, and
1036@file{wchar.h}, which must come from a separate C library implementation.
1037Because of this the GNU C compiler does not define macro
1038@code{__STDC_DEC_FP__} to indicate that the implementation conforms to
1039the technical report.
1040@end itemize
1041
1042Types @code{_Decimal32}, @code{_Decimal64}, and @code{_Decimal128}
1043are supported by the DWARF2 debug information format.
1044
1045@node Hex Floats
1046@section Hex Floats
1047@cindex hex floats
1048
1049ISO C99 supports floating-point numbers written not only in the usual
1050decimal notation, such as @code{1.55e1}, but also numbers such as
1051@code{0x1.fp3} written in hexadecimal format. As a GNU extension, GCC
1052supports this in C90 mode (except in some cases when strictly
1053conforming) and in C++. In that format the
1054@samp{0x} hex introducer and the @samp{p} or @samp{P} exponent field are
1055mandatory. The exponent is a decimal number that indicates the power of
10562 by which the significant part will be multiplied. Thus @samp{0x1.f} is
1057@tex
1058$1 {15\over16}$,
1059@end tex
1060@ifnottex
10611 15/16,
1062@end ifnottex
1063@samp{p3} multiplies it by 8, and the value of @code{0x1.fp3}
1064is the same as @code{1.55e1}.
1065
1066Unlike for floating-point numbers in the decimal notation the exponent
1067is always required in the hexadecimal notation. Otherwise the compiler
1068would not be able to resolve the ambiguity of, e.g., @code{0x1.f}. This
1069could mean @code{1.0f} or @code{1.9375} since @samp{f} is also the
1070extension for floating-point constants of type @code{float}.
1071
1072@node Fixed-Point
1073@section Fixed-Point Types
1074@cindex fixed-point types
1075@cindex @code{_Fract} data type
1076@cindex @code{_Accum} data type
1077@cindex @code{_Sat} data type
1078@cindex @code{hr} fixed-suffix
1079@cindex @code{r} fixed-suffix
1080@cindex @code{lr} fixed-suffix
1081@cindex @code{llr} fixed-suffix
1082@cindex @code{uhr} fixed-suffix
1083@cindex @code{ur} fixed-suffix
1084@cindex @code{ulr} fixed-suffix
1085@cindex @code{ullr} fixed-suffix
1086@cindex @code{hk} fixed-suffix
1087@cindex @code{k} fixed-suffix
1088@cindex @code{lk} fixed-suffix
1089@cindex @code{llk} fixed-suffix
1090@cindex @code{uhk} fixed-suffix
1091@cindex @code{uk} fixed-suffix
1092@cindex @code{ulk} fixed-suffix
1093@cindex @code{ullk} fixed-suffix
1094@cindex @code{HR} fixed-suffix
1095@cindex @code{R} fixed-suffix
1096@cindex @code{LR} fixed-suffix
1097@cindex @code{LLR} fixed-suffix
1098@cindex @code{UHR} fixed-suffix
1099@cindex @code{UR} fixed-suffix
1100@cindex @code{ULR} fixed-suffix
1101@cindex @code{ULLR} fixed-suffix
1102@cindex @code{HK} fixed-suffix
1103@cindex @code{K} fixed-suffix
1104@cindex @code{LK} fixed-suffix
1105@cindex @code{LLK} fixed-suffix
1106@cindex @code{UHK} fixed-suffix
1107@cindex @code{UK} fixed-suffix
1108@cindex @code{ULK} fixed-suffix
1109@cindex @code{ULLK} fixed-suffix
1110
1111As an extension, the GNU C compiler supports fixed-point types as
1112defined in the N1169 draft of ISO/IEC DTR 18037. Support for fixed-point
1113types in GCC will evolve as the draft technical report changes.
1114Calling conventions for any target might also change. Not all targets
1115support fixed-point types.
1116
1117The fixed-point types are
1118@code{short _Fract},
1119@code{_Fract},
1120@code{long _Fract},
1121@code{long long _Fract},
1122@code{unsigned short _Fract},
1123@code{unsigned _Fract},
1124@code{unsigned long _Fract},
1125@code{unsigned long long _Fract},
1126@code{_Sat short _Fract},
1127@code{_Sat _Fract},
1128@code{_Sat long _Fract},
1129@code{_Sat long long _Fract},
1130@code{_Sat unsigned short _Fract},
1131@code{_Sat unsigned _Fract},
1132@code{_Sat unsigned long _Fract},
1133@code{_Sat unsigned long long _Fract},
1134@code{short _Accum},
1135@code{_Accum},
1136@code{long _Accum},
1137@code{long long _Accum},
1138@code{unsigned short _Accum},
1139@code{unsigned _Accum},
1140@code{unsigned long _Accum},
1141@code{unsigned long long _Accum},
1142@code{_Sat short _Accum},
1143@code{_Sat _Accum},
1144@code{_Sat long _Accum},
1145@code{_Sat long long _Accum},
1146@code{_Sat unsigned short _Accum},
1147@code{_Sat unsigned _Accum},
1148@code{_Sat unsigned long _Accum},
1149@code{_Sat unsigned long long _Accum}.
1150
1151Fixed-point data values contain fractional and optional integral parts.
1152The format of fixed-point data varies and depends on the target machine.
1153
1154Support for fixed-point types includes:
1155@itemize @bullet
1156@item
1157prefix and postfix increment and decrement operators (@code{++}, @code{--})
1158@item
1159unary arithmetic operators (@code{+}, @code{-}, @code{!})
1160@item
1161binary arithmetic operators (@code{+}, @code{-}, @code{*}, @code{/})
1162@item
1163binary shift operators (@code{<<}, @code{>>})
1164@item
1165relational operators (@code{<}, @code{<=}, @code{>=}, @code{>})
1166@item
1167equality operators (@code{==}, @code{!=})
1168@item
1169assignment operators (@code{+=}, @code{-=}, @code{*=}, @code{/=},
1170@code{<<=}, @code{>>=})
1171@item
1172conversions to and from integer, floating-point, or fixed-point types
1173@end itemize
1174
1175Use a suffix in a fixed-point literal constant:
1176@itemize
1177@item @samp{hr} or @samp{HR} for @code{short _Fract} and
1178@code{_Sat short _Fract}
1179@item @samp{r} or @samp{R} for @code{_Fract} and @code{_Sat _Fract}
1180@item @samp{lr} or @samp{LR} for @code{long _Fract} and
1181@code{_Sat long _Fract}
1182@item @samp{llr} or @samp{LLR} for @code{long long _Fract} and
1183@code{_Sat long long _Fract}
1184@item @samp{uhr} or @samp{UHR} for @code{unsigned short _Fract} and
1185@code{_Sat unsigned short _Fract}
1186@item @samp{ur} or @samp{UR} for @code{unsigned _Fract} and
1187@code{_Sat unsigned _Fract}
1188@item @samp{ulr} or @samp{ULR} for @code{unsigned long _Fract} and
1189@code{_Sat unsigned long _Fract}
1190@item @samp{ullr} or @samp{ULLR} for @code{unsigned long long _Fract}
1191and @code{_Sat unsigned long long _Fract}
1192@item @samp{hk} or @samp{HK} for @code{short _Accum} and
1193@code{_Sat short _Accum}
1194@item @samp{k} or @samp{K} for @code{_Accum} and @code{_Sat _Accum}
1195@item @samp{lk} or @samp{LK} for @code{long _Accum} and
1196@code{_Sat long _Accum}
1197@item @samp{llk} or @samp{LLK} for @code{long long _Accum} and
1198@code{_Sat long long _Accum}
1199@item @samp{uhk} or @samp{UHK} for @code{unsigned short _Accum} and
1200@code{_Sat unsigned short _Accum}
1201@item @samp{uk} or @samp{UK} for @code{unsigned _Accum} and
1202@code{_Sat unsigned _Accum}
1203@item @samp{ulk} or @samp{ULK} for @code{unsigned long _Accum} and
1204@code{_Sat unsigned long _Accum}
1205@item @samp{ullk} or @samp{ULLK} for @code{unsigned long long _Accum}
1206and @code{_Sat unsigned long long _Accum}
1207@end itemize
1208
1209GCC support of fixed-point types as specified by the draft technical report
1210is incomplete:
1211
1212@itemize @bullet
1213@item
1214Pragmas to control overflow and rounding behaviors are not implemented.
1215@end itemize
1216
1217Fixed-point types are supported by the DWARF2 debug information format.
1218
1219@node Named Address Spaces
1220@section Named Address Spaces
1221@cindex Named Address Spaces
1222
1223As an extension, the GNU C compiler supports named address spaces as
1224defined in the N1275 draft of ISO/IEC DTR 18037. Support for named
1225address spaces in GCC will evolve as the draft technical report
1226changes. Calling conventions for any target might also change. At
1227present, only the AVR, SPU, M32C, and RL78 targets support address
1228spaces other than the generic address space.
1229
1230Address space identifiers may be used exactly like any other C type
1231qualifier (e.g., @code{const} or @code{volatile}). See the N1275
1232document for more details.
1233
1234@anchor{AVR Named Address Spaces}
1235@subsection AVR Named Address Spaces
1236
1237On the AVR target, there are several address spaces that can be used
1238in order to put read-only data into the flash memory and access that
1239data by means of the special instructions @code{LPM} or @code{ELPM}
1240needed to read from flash.
1241
1242Per default, any data including read-only data is located in RAM
1243(the generic address space) so that non-generic address spaces are
1244needed to locate read-only data in flash memory
1245@emph{and} to generate the right instructions to access this data
1246without using (inline) assembler code.
1247
1248@table @code
1249@item __flash
1250@cindex @code{__flash} AVR Named Address Spaces
1251The @code{__flash} qualifier will locate data in the
1252@code{.progmem.data} section. Data will be read using the @code{LPM}
1253instruction. Pointers to this address space are 16 bits wide.
1254
1255@item __flash1
1256@item __flash2
1257@item __flash3
1258@item __flash4
1259@item __flash5
1260@cindex @code{__flash1} AVR Named Address Spaces
1261@cindex @code{__flash2} AVR Named Address Spaces
1262@cindex @code{__flash3} AVR Named Address Spaces
1263@cindex @code{__flash4} AVR Named Address Spaces
1264@cindex @code{__flash5} AVR Named Address Spaces
1265These are 16-bit address spaces locating data in section
1266@code{.progmem@var{N}.data} where @var{N} refers to
1267address space @code{__flash@var{N}}.
1268The compiler will set the @code{RAMPZ} segment register approptiately
1269before reading data by means of the @code{ELPM} instruction.
1270
1271@item __memx
1272@cindex @code{__memx} AVR Named Address Spaces
1273This is a 24-bit address space that linearizes flash and RAM:
1274If the high bit of the address is set, data is read from
1275RAM using the lower two bytes as RAM address.
1276If the high bit of the address is clear, data is read from flash
1277with @code{RAMPZ} set according to the high byte of the address.
1278
5ce9237c 1279Objects in this address space will be located in @code{.progmemx.data}.
e4b17023
JM
1280@end table
1281
1282@b{Example}
1283
1284@example
1285char my_read (const __flash char ** p)
1286@{
1287 /* p is a pointer to RAM that points to a pointer to flash.
1288 The first indirection of p will read that flash pointer
1289 from RAM and the second indirection reads a char from this
1290 flash address. */
1291
1292 return **p;
1293@}
1294
1295/* Locate array[] in flash memory */
1296const __flash int array[] = @{ 3, 5, 7, 11, 13, 17, 19 @};
1297
1298int i = 1;
1299
1300int main (void)
1301@{
1302 /* Return 17 by reading from flash memory */
1303 return array[array[i]];
1304@}
1305@end example
1306
1307For each named address space supported by avr-gcc there is an equally
1308named but uppercase built-in macro defined.
1309The purpose is to facilitate testing if respective address space
1310support is available or not:
1311
1312@example
1313#ifdef __FLASH
1314const __flash int var = 1;
1315
1316int read_var (void)
1317@{
1318 return var;
1319@}
1320#else
1321#include <avr/pgmspace.h> /* From AVR-LibC */
1322
1323const int var PROGMEM = 1;
1324
1325int read_var (void)
1326@{
1327 return (int) pgm_read_word (&var);
1328@}
1329#endif /* __FLASH */
1330@end example
1331
1332Notice that attribute @ref{AVR Variable Attributes,@code{progmem}}
1333locates data in flash but
1334accesses to these data will read from generic address space, i.e.@:
1335from RAM,
1336so that you need special accessors like @code{pgm_read_byte}
5ce9237c 1337from @w{@uref{http://nongnu.org/avr-libc/user-manual/,AVR-LibC}}
e4b17023
JM
1338together with attribute @code{progmem}.
1339
1340@b{Limitations and caveats}
1341
1342@itemize
1343@item
1344Reading across the 64@tie{}KiB section boundary of
1345the @code{__flash} or @code{__flash@var{N}} address spaces
1346will show undefined behaviour. The only address space that
1347supports reading across the 64@tie{}KiB flash segment boundaries is
1348@code{__memx}.
1349
1350@item
1351If you use one of the @code{__flash@var{N}} address spaces
1352you will have to arrange your linker skript to locate the
1353@code{.progmem@var{N}.data} sections according to your needs.
1354
1355@item
1356Any data or pointers to the non-generic address spaces must
1357be qualified as @code{const}, i.e.@: as read-only data.
1358This still applies if the data in one of these address
1359spaces like software version number or calibration lookup table are intended to
1360be changed after load time by, say, a boot loader. In this case
1361the right qualification is @code{const} @code{volatile} so that the compiler
1362must not optimize away known values or insert them
1363as immediates into operands of instructions.
1364
1365@item
1366Code like the following is not yet supported because of missing
1367support in avr-binutils,
1368see @w{@uref{http://sourceware.org/PR13503,PR13503}}.
1369@example
1370extern const __memx char foo;
1371const __memx void *pfoo = &foo;
1372@end example
1373The code will throw an assembler warning and the high byte of
1374@code{pfoo} will be initialized with@tie{}@code{0}, i.e.@: the
1375initialization will be as if @code{foo} was located in the first
137664@tie{}KiB chunk of flash.
1377
1378@end itemize
1379
1380@subsection M32C Named Address Spaces
1381@cindex @code{__far} M32C Named Address Spaces
1382
1383On the M32C target, with the R8C and M16C cpu variants, variables
1384qualified with @code{__far} are accessed using 32-bit addresses in
1385order to access memory beyond the first 64@tie{}Ki bytes. If
1386@code{__far} is used with the M32CM or M32C cpu variants, it has no
1387effect.
1388
1389@subsection RL78 Named Address Spaces
1390@cindex @code{__far} RL78 Named Address Spaces
1391
1392On the RL78 target, variables qualified with @code{__far} are accessed
1393with 32-bit pointers (20-bit addresses) rather than the default 16-bit
1394addresses. Non-far variables are assumed to appear in the topmost
139564@tie{}KiB of the address space.
1396
1397@subsection SPU Named Address Spaces
1398@cindex @code{__ea} SPU Named Address Spaces
1399
1400On the SPU target variables may be declared as
1401belonging to another address space by qualifying the type with the
1402@code{__ea} address space identifier:
1403
1404@smallexample
1405extern int __ea i;
1406@end smallexample
1407
1408When the variable @code{i} is accessed, the compiler will generate
1409special code to access this variable. It may use runtime library
1410support, or generate special machine instructions to access that address
1411space.
1412
1413@node Zero Length
1414@section Arrays of Length Zero
1415@cindex arrays of length zero
1416@cindex zero-length arrays
1417@cindex length-zero arrays
1418@cindex flexible array members
1419
1420Zero-length arrays are allowed in GNU C@. They are very useful as the
1421last element of a structure which is really a header for a variable-length
1422object:
1423
1424@smallexample
1425struct line @{
1426 int length;
1427 char contents[0];
1428@};
1429
1430struct line *thisline = (struct line *)
1431 malloc (sizeof (struct line) + this_length);
1432thisline->length = this_length;
1433@end smallexample
1434
1435In ISO C90, you would have to give @code{contents} a length of 1, which
1436means either you waste space or complicate the argument to @code{malloc}.
1437
1438In ISO C99, you would use a @dfn{flexible array member}, which is
1439slightly different in syntax and semantics:
1440
1441@itemize @bullet
1442@item
1443Flexible array members are written as @code{contents[]} without
1444the @code{0}.
1445
1446@item
1447Flexible array members have incomplete type, and so the @code{sizeof}
1448operator may not be applied. As a quirk of the original implementation
1449of zero-length arrays, @code{sizeof} evaluates to zero.
1450
1451@item
1452Flexible array members may only appear as the last member of a
1453@code{struct} that is otherwise non-empty.
1454
1455@item
1456A structure containing a flexible array member, or a union containing
1457such a structure (possibly recursively), may not be a member of a
1458structure or an element of an array. (However, these uses are
1459permitted by GCC as extensions.)
1460@end itemize
1461
1462GCC versions before 3.0 allowed zero-length arrays to be statically
1463initialized, as if they were flexible arrays. In addition to those
1464cases that were useful, it also allowed initializations in situations
1465that would corrupt later data. Non-empty initialization of zero-length
1466arrays is now treated like any case where there are more initializer
1467elements than the array holds, in that a suitable warning about "excess
1468elements in array" is given, and the excess elements (all of them, in
1469this case) are ignored.
1470
1471Instead GCC allows static initialization of flexible array members.
1472This is equivalent to defining a new structure containing the original
1473structure followed by an array of sufficient size to contain the data.
1474I.e.@: in the following, @code{f1} is constructed as if it were declared
1475like @code{f2}.
1476
1477@smallexample
1478struct f1 @{
1479 int x; int y[];
1480@} f1 = @{ 1, @{ 2, 3, 4 @} @};
1481
1482struct f2 @{
1483 struct f1 f1; int data[3];
1484@} f2 = @{ @{ 1 @}, @{ 2, 3, 4 @} @};
1485@end smallexample
1486
1487@noindent
1488The convenience of this extension is that @code{f1} has the desired
1489type, eliminating the need to consistently refer to @code{f2.f1}.
1490
1491This has symmetry with normal static arrays, in that an array of
1492unknown size is also written with @code{[]}.
1493
1494Of course, this extension only makes sense if the extra data comes at
1495the end of a top-level object, as otherwise we would be overwriting
1496data at subsequent offsets. To avoid undue complication and confusion
1497with initialization of deeply nested arrays, we simply disallow any
1498non-empty initialization except when the structure is the top-level
1499object. For example:
1500
1501@smallexample
1502struct foo @{ int x; int y[]; @};
1503struct bar @{ struct foo z; @};
1504
1505struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
1506struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
1507struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
1508struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
1509@end smallexample
1510
1511@node Empty Structures
1512@section Structures With No Members
1513@cindex empty structures
1514@cindex zero-size structures
1515
1516GCC permits a C structure to have no members:
1517
1518@smallexample
1519struct empty @{
1520@};
1521@end smallexample
1522
1523The structure will have size zero. In C++, empty structures are part
1524of the language. G++ treats empty structures as if they had a single
1525member of type @code{char}.
1526
1527@node Variable Length
1528@section Arrays of Variable Length
1529@cindex variable-length arrays
1530@cindex arrays of variable length
1531@cindex VLAs
1532
1533Variable-length automatic arrays are allowed in ISO C99, and as an
1534extension GCC accepts them in C90 mode and in C++. These arrays are
1535declared like any other automatic arrays, but with a length that is not
1536a constant expression. The storage is allocated at the point of
1537declaration and deallocated when the brace-level is exited. For
1538example:
1539
1540@smallexample
1541FILE *
1542concat_fopen (char *s1, char *s2, char *mode)
1543@{
1544 char str[strlen (s1) + strlen (s2) + 1];
1545 strcpy (str, s1);
1546 strcat (str, s2);
1547 return fopen (str, mode);
1548@}
1549@end smallexample
1550
1551@cindex scope of a variable length array
1552@cindex variable-length array scope
1553@cindex deallocating variable length arrays
1554Jumping or breaking out of the scope of the array name deallocates the
1555storage. Jumping into the scope is not allowed; you get an error
1556message for it.
1557
1558@cindex @code{alloca} vs variable-length arrays
1559You can use the function @code{alloca} to get an effect much like
1560variable-length arrays. The function @code{alloca} is available in
1561many other C implementations (but not in all). On the other hand,
1562variable-length arrays are more elegant.
1563
1564There are other differences between these two methods. Space allocated
1565with @code{alloca} exists until the containing @emph{function} returns.
1566The space for a variable-length array is deallocated as soon as the array
1567name's scope ends. (If you use both variable-length arrays and
1568@code{alloca} in the same function, deallocation of a variable-length array
1569will also deallocate anything more recently allocated with @code{alloca}.)
1570
1571You can also use variable-length arrays as arguments to functions:
1572
1573@smallexample
1574struct entry
1575tester (int len, char data[len][len])
1576@{
1577 /* @r{@dots{}} */
1578@}
1579@end smallexample
1580
1581The length of an array is computed once when the storage is allocated
1582and is remembered for the scope of the array in case you access it with
1583@code{sizeof}.
1584
1585If you want to pass the array first and the length afterward, you can
1586use a forward declaration in the parameter list---another GNU extension.
1587
1588@smallexample
1589struct entry
1590tester (int len; char data[len][len], int len)
1591@{
1592 /* @r{@dots{}} */
1593@}
1594@end smallexample
1595
1596@cindex parameter forward declaration
1597The @samp{int len} before the semicolon is a @dfn{parameter forward
1598declaration}, and it serves the purpose of making the name @code{len}
1599known when the declaration of @code{data} is parsed.
1600
1601You can write any number of such parameter forward declarations in the
1602parameter list. They can be separated by commas or semicolons, but the
1603last one must end with a semicolon, which is followed by the ``real''
1604parameter declarations. Each forward declaration must match a ``real''
1605declaration in parameter name and data type. ISO C99 does not support
1606parameter forward declarations.
1607
1608@node Variadic Macros
1609@section Macros with a Variable Number of Arguments.
1610@cindex variable number of arguments
1611@cindex macro with variable arguments
1612@cindex rest argument (in macro)
1613@cindex variadic macros
1614
1615In the ISO C standard of 1999, a macro can be declared to accept a
1616variable number of arguments much as a function can. The syntax for
1617defining the macro is similar to that of a function. Here is an
1618example:
1619
1620@smallexample
1621#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)
1622@end smallexample
1623
1624Here @samp{@dots{}} is a @dfn{variable argument}. In the invocation of
1625such a macro, it represents the zero or more tokens until the closing
1626parenthesis that ends the invocation, including any commas. This set of
1627tokens replaces the identifier @code{__VA_ARGS__} in the macro body
1628wherever it appears. See the CPP manual for more information.
1629
1630GCC has long supported variadic macros, and used a different syntax that
1631allowed you to give a name to the variable arguments just like any other
1632argument. Here is an example:
1633
1634@smallexample
1635#define debug(format, args...) fprintf (stderr, format, args)
1636@end smallexample
1637
1638This is in all ways equivalent to the ISO C example above, but arguably
1639more readable and descriptive.
1640
1641GNU CPP has two further variadic macro extensions, and permits them to
1642be used with either of the above forms of macro definition.
1643
1644In standard C, you are not allowed to leave the variable argument out
1645entirely; but you are allowed to pass an empty argument. For example,
1646this invocation is invalid in ISO C, because there is no comma after
1647the string:
1648
1649@smallexample
1650debug ("A message")
1651@end smallexample
1652
1653GNU CPP permits you to completely omit the variable arguments in this
1654way. In the above examples, the compiler would complain, though since
1655the expansion of the macro still has the extra comma after the format
1656string.
1657
1658To help solve this problem, CPP behaves specially for variable arguments
1659used with the token paste operator, @samp{##}. If instead you write
1660
1661@smallexample
1662#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
1663@end smallexample
1664
1665and if the variable arguments are omitted or empty, the @samp{##}
1666operator causes the preprocessor to remove the comma before it. If you
1667do provide some variable arguments in your macro invocation, GNU CPP
1668does not complain about the paste operation and instead places the
1669variable arguments after the comma. Just like any other pasted macro
1670argument, these arguments are not macro expanded.
1671
1672@node Escaped Newlines
1673@section Slightly Looser Rules for Escaped Newlines
1674@cindex escaped newlines
1675@cindex newlines (escaped)
1676
1677Recently, the preprocessor has relaxed its treatment of escaped
1678newlines. Previously, the newline had to immediately follow a
1679backslash. The current implementation allows whitespace in the form
1680of spaces, horizontal and vertical tabs, and form feeds between the
1681backslash and the subsequent newline. The preprocessor issues a
1682warning, but treats it as a valid escaped newline and combines the two
1683lines to form a single logical line. This works within comments and
1684tokens, as well as between tokens. Comments are @emph{not} treated as
1685whitespace for the purposes of this relaxation, since they have not
1686yet been replaced with spaces.
1687
1688@node Subscripting
1689@section Non-Lvalue Arrays May Have Subscripts
1690@cindex subscripting
1691@cindex arrays, non-lvalue
1692
1693@cindex subscripting and function values
1694In ISO C99, arrays that are not lvalues still decay to pointers, and
1695may be subscripted, although they may not be modified or used after
1696the next sequence point and the unary @samp{&} operator may not be
1697applied to them. As an extension, GCC allows such arrays to be
1698subscripted in C90 mode, though otherwise they do not decay to
1699pointers outside C99 mode. For example,
1700this is valid in GNU C though not valid in C90:
1701
1702@smallexample
1703@group
1704struct foo @{int a[4];@};
1705
1706struct foo f();
1707
1708bar (int index)
1709@{
1710 return f().a[index];
1711@}
1712@end group
1713@end smallexample
1714
1715@node Pointer Arith
1716@section Arithmetic on @code{void}- and Function-Pointers
1717@cindex void pointers, arithmetic
1718@cindex void, size of pointer to
1719@cindex function pointers, arithmetic
1720@cindex function, size of pointer to
1721
1722In GNU C, addition and subtraction operations are supported on pointers to
1723@code{void} and on pointers to functions. This is done by treating the
1724size of a @code{void} or of a function as 1.
1725
1726A consequence of this is that @code{sizeof} is also allowed on @code{void}
1727and on function types, and returns 1.
1728
1729@opindex Wpointer-arith
1730The option @option{-Wpointer-arith} requests a warning if these extensions
1731are used.
1732
1733@node Initializers
1734@section Non-Constant Initializers
1735@cindex initializers, non-constant
1736@cindex non-constant initializers
1737
1738As in standard C++ and ISO C99, the elements of an aggregate initializer for an
1739automatic variable are not required to be constant expressions in GNU C@.
1740Here is an example of an initializer with run-time varying elements:
1741
1742@smallexample
1743foo (float f, float g)
1744@{
1745 float beat_freqs[2] = @{ f-g, f+g @};
1746 /* @r{@dots{}} */
1747@}
1748@end smallexample
1749
1750@node Compound Literals
1751@section Compound Literals
1752@cindex constructor expressions
1753@cindex initializations in expressions
1754@cindex structures, constructor expression
1755@cindex expressions, constructor
1756@cindex compound literals
1757@c The GNU C name for what C99 calls compound literals was "constructor expressions".
1758
1759ISO C99 supports compound literals. A compound literal looks like
1760a cast containing an initializer. Its value is an object of the
1761type specified in the cast, containing the elements specified in
1762the initializer; it is an lvalue. As an extension, GCC supports
1763compound literals in C90 mode and in C++, though the semantics are
1764somewhat different in C++.
1765
1766Usually, the specified type is a structure. Assume that
1767@code{struct foo} and @code{structure} are declared as shown:
1768
1769@smallexample
1770struct foo @{int a; char b[2];@} structure;
1771@end smallexample
1772
1773@noindent
1774Here is an example of constructing a @code{struct foo} with a compound literal:
1775
1776@smallexample
1777structure = ((struct foo) @{x + y, 'a', 0@});
1778@end smallexample
1779
1780@noindent
1781This is equivalent to writing the following:
1782
1783@smallexample
1784@{
1785 struct foo temp = @{x + y, 'a', 0@};
1786 structure = temp;
1787@}
1788@end smallexample
1789
1790You can also construct an array, though this is dangerous in C++, as
1791explained below. If all the elements of the compound literal are
1792(made up of) simple constant expressions, suitable for use in
1793initializers of objects of static storage duration, then the compound
1794literal can be coerced to a pointer to its first element and used in
1795such an initializer, as shown here:
1796
1797@smallexample
1798char **foo = (char *[]) @{ "x", "y", "z" @};
1799@end smallexample
1800
1801Compound literals for scalar types and union types are
1802also allowed, but then the compound literal is equivalent
1803to a cast.
1804
1805As a GNU extension, GCC allows initialization of objects with static storage
1806duration by compound literals (which is not possible in ISO C99, because
1807the initializer is not a constant).
1808It is handled as if the object was initialized only with the bracket
1809enclosed list if the types of the compound literal and the object match.
1810The initializer list of the compound literal must be constant.
1811If the object being initialized has array type of unknown size, the size is
1812determined by compound literal size.
1813
1814@smallexample
1815static struct foo x = (struct foo) @{1, 'a', 'b'@};
1816static int y[] = (int []) @{1, 2, 3@};
1817static int z[] = (int [3]) @{1@};
1818@end smallexample
1819
1820@noindent
1821The above lines are equivalent to the following:
1822@smallexample
1823static struct foo x = @{1, 'a', 'b'@};
1824static int y[] = @{1, 2, 3@};
1825static int z[] = @{1, 0, 0@};
1826@end smallexample
1827
1828In C, a compound literal designates an unnamed object with static or
1829automatic storage duration. In C++, a compound literal designates a
1830temporary object, which only lives until the end of its
1831full-expression. As a result, well-defined C code that takes the
1832address of a subobject of a compound literal can be undefined in C++.
1833For instance, if the array compound literal example above appeared
1834inside a function, any subsequent use of @samp{foo} in C++ has
1835undefined behavior because the lifetime of the array ends after the
1836declaration of @samp{foo}. As a result, the C++ compiler now rejects
1837the conversion of a temporary array to a pointer.
1838
1839As an optimization, the C++ compiler sometimes gives array compound
1840literals longer lifetimes: when the array either appears outside a
1841function or has const-qualified type. If @samp{foo} and its
1842initializer had elements of @samp{char *const} type rather than
1843@samp{char *}, or if @samp{foo} were a global variable, the array
1844would have static storage duration. But it is probably safest just to
1845avoid the use of array compound literals in code compiled as C++.
1846
1847@node Designated Inits
1848@section Designated Initializers
1849@cindex initializers with labeled elements
1850@cindex labeled elements in initializers
1851@cindex case labels in initializers
1852@cindex designated initializers
1853
1854Standard C90 requires the elements of an initializer to appear in a fixed
1855order, the same as the order of the elements in the array or structure
1856being initialized.
1857
1858In ISO C99 you can give the elements in any order, specifying the array
1859indices or structure field names they apply to, and GNU C allows this as
1860an extension in C90 mode as well. This extension is not
1861implemented in GNU C++.
1862
1863To specify an array index, write
1864@samp{[@var{index}] =} before the element value. For example,
1865
1866@smallexample
1867int a[6] = @{ [4] = 29, [2] = 15 @};
1868@end smallexample
1869
1870@noindent
1871is equivalent to
1872
1873@smallexample
1874int a[6] = @{ 0, 0, 15, 0, 29, 0 @};
1875@end smallexample
1876
1877@noindent
1878The index values must be constant expressions, even if the array being
1879initialized is automatic.
1880
1881An alternative syntax for this which has been obsolete since GCC 2.5 but
1882GCC still accepts is to write @samp{[@var{index}]} before the element
1883value, with no @samp{=}.
1884
1885To initialize a range of elements to the same value, write
1886@samp{[@var{first} ... @var{last}] = @var{value}}. This is a GNU
1887extension. For example,
1888
1889@smallexample
1890int widths[] = @{ [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 @};
1891@end smallexample
1892
1893@noindent
1894If the value in it has side-effects, the side-effects will happen only once,
1895not for each initialized field by the range initializer.
1896
1897@noindent
1898Note that the length of the array is the highest value specified
1899plus one.
1900
1901In a structure initializer, specify the name of a field to initialize
1902with @samp{.@var{fieldname} =} before the element value. For example,
1903given the following structure,
1904
1905@smallexample
1906struct point @{ int x, y; @};
1907@end smallexample
1908
1909@noindent
1910the following initialization
1911
1912@smallexample
1913struct point p = @{ .y = yvalue, .x = xvalue @};
1914@end smallexample
1915
1916@noindent
1917is equivalent to
1918
1919@smallexample
1920struct point p = @{ xvalue, yvalue @};
1921@end smallexample
1922
1923Another syntax which has the same meaning, obsolete since GCC 2.5, is
1924@samp{@var{fieldname}:}, as shown here:
1925
1926@smallexample
1927struct point p = @{ y: yvalue, x: xvalue @};
1928@end smallexample
1929
1930@cindex designators
1931The @samp{[@var{index}]} or @samp{.@var{fieldname}} is known as a
1932@dfn{designator}. You can also use a designator (or the obsolete colon
1933syntax) when initializing a union, to specify which element of the union
1934should be used. For example,
1935
1936@smallexample
1937union foo @{ int i; double d; @};
1938
1939union foo f = @{ .d = 4 @};
1940@end smallexample
1941
1942@noindent
1943will convert 4 to a @code{double} to store it in the union using
1944the second element. By contrast, casting 4 to type @code{union foo}
1945would store it into the union as the integer @code{i}, since it is
1946an integer. (@xref{Cast to Union}.)
1947
1948You can combine this technique of naming elements with ordinary C
1949initialization of successive elements. Each initializer element that
1950does not have a designator applies to the next consecutive element of the
1951array or structure. For example,
1952
1953@smallexample
1954int a[6] = @{ [1] = v1, v2, [4] = v4 @};
1955@end smallexample
1956
1957@noindent
1958is equivalent to
1959
1960@smallexample
1961int a[6] = @{ 0, v1, v2, 0, v4, 0 @};
1962@end smallexample
1963
1964Labeling the elements of an array initializer is especially useful
1965when the indices are characters or belong to an @code{enum} type.
1966For example:
1967
1968@smallexample
1969int whitespace[256]
1970 = @{ [' '] = 1, ['\t'] = 1, ['\h'] = 1,
1971 ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 @};
1972@end smallexample
1973
1974@cindex designator lists
1975You can also write a series of @samp{.@var{fieldname}} and
1976@samp{[@var{index}]} designators before an @samp{=} to specify a
1977nested subobject to initialize; the list is taken relative to the
1978subobject corresponding to the closest surrounding brace pair. For
1979example, with the @samp{struct point} declaration above:
1980
1981@smallexample
1982struct point ptarray[10] = @{ [2].y = yv2, [2].x = xv2, [0].x = xv0 @};
1983@end smallexample
1984
1985@noindent
1986If the same field is initialized multiple times, it will have value from
1987the last initialization. If any such overridden initialization has
1988side-effect, it is unspecified whether the side-effect happens or not.
1989Currently, GCC will discard them and issue a warning.
1990
1991@node Case Ranges
1992@section Case Ranges
1993@cindex case ranges
1994@cindex ranges in case statements
1995
1996You can specify a range of consecutive values in a single @code{case} label,
1997like this:
1998
1999@smallexample
2000case @var{low} ... @var{high}:
2001@end smallexample
2002
2003@noindent
2004This has the same effect as the proper number of individual @code{case}
2005labels, one for each integer value from @var{low} to @var{high}, inclusive.
2006
2007This feature is especially useful for ranges of ASCII character codes:
2008
2009@smallexample
2010case 'A' ... 'Z':
2011@end smallexample
2012
2013@strong{Be careful:} Write spaces around the @code{...}, for otherwise
2014it may be parsed wrong when you use it with integer values. For example,
2015write this:
2016
2017@smallexample
2018case 1 ... 5:
2019@end smallexample
2020
2021@noindent
2022rather than this:
2023
2024@smallexample
2025case 1...5:
2026@end smallexample
2027
2028@node Cast to Union
2029@section Cast to a Union Type
2030@cindex cast to a union
2031@cindex union, casting to a
2032
2033A cast to union type is similar to other casts, except that the type
2034specified is a union type. You can specify the type either with
2035@code{union @var{tag}} or with a typedef name. A cast to union is actually
2036a constructor though, not a cast, and hence does not yield an lvalue like
2037normal casts. (@xref{Compound Literals}.)
2038
2039The types that may be cast to the union type are those of the members
2040of the union. Thus, given the following union and variables:
2041
2042@smallexample
2043union foo @{ int i; double d; @};
2044int x;
2045double y;
2046@end smallexample
2047
2048@noindent
2049both @code{x} and @code{y} can be cast to type @code{union foo}.
2050
2051Using the cast as the right-hand side of an assignment to a variable of
2052union type is equivalent to storing in a member of the union:
2053
2054@smallexample
2055union foo u;
2056/* @r{@dots{}} */
2057u = (union foo) x @equiv{} u.i = x
2058u = (union foo) y @equiv{} u.d = y
2059@end smallexample
2060
2061You can also use the union cast as a function argument:
2062
2063@smallexample
2064void hack (union foo);
2065/* @r{@dots{}} */
2066hack ((union foo) x);
2067@end smallexample
2068
2069@node Mixed Declarations
2070@section Mixed Declarations and Code
2071@cindex mixed declarations and code
2072@cindex declarations, mixed with code
2073@cindex code, mixed with declarations
2074
2075ISO C99 and ISO C++ allow declarations and code to be freely mixed
2076within compound statements. As an extension, GCC also allows this in
2077C90 mode. For example, you could do:
2078
2079@smallexample
2080int i;
2081/* @r{@dots{}} */
2082i++;
2083int j = i + 2;
2084@end smallexample
2085
2086Each identifier is visible from where it is declared until the end of
2087the enclosing block.
2088
2089@node Function Attributes
2090@section Declaring Attributes of Functions
2091@cindex function attributes
2092@cindex declaring attributes of functions
2093@cindex functions that never return
2094@cindex functions that return more than once
2095@cindex functions that have no side effects
2096@cindex functions in arbitrary sections
2097@cindex functions that behave like malloc
2098@cindex @code{volatile} applied to function
2099@cindex @code{const} applied to function
2100@cindex functions with @code{printf}, @code{scanf}, @code{strftime} or @code{strfmon} style arguments
2101@cindex functions with non-null pointer arguments
2102@cindex functions that are passed arguments in registers on the 386
2103@cindex functions that pop the argument stack on the 386
2104@cindex functions that do not pop the argument stack on the 386
2105@cindex functions that have different compilation options on the 386
2106@cindex functions that have different optimization options
2107@cindex functions that are dynamically resolved
2108
2109In GNU C, you declare certain things about functions called in your program
2110which help the compiler optimize function calls and check your code more
2111carefully.
2112
2113The keyword @code{__attribute__} allows you to specify special
2114attributes when making a declaration. This keyword is followed by an
2115attribute specification inside double parentheses. The following
2116attributes are currently defined for functions on all targets:
2117@code{aligned}, @code{alloc_size}, @code{noreturn},
2118@code{returns_twice}, @code{noinline}, @code{noclone},
2119@code{always_inline}, @code{flatten}, @code{pure}, @code{const},
2120@code{nothrow}, @code{sentinel}, @code{format}, @code{format_arg},
2121@code{no_instrument_function}, @code{no_split_stack},
2122@code{section}, @code{constructor},
2123@code{destructor}, @code{used}, @code{unused}, @code{deprecated},
2124@code{weak}, @code{malloc}, @code{alias}, @code{ifunc},
2125@code{warn_unused_result}, @code{nonnull}, @code{gnu_inline},
2126@code{externally_visible}, @code{hot}, @code{cold}, @code{artificial},
2127@code{error} and @code{warning}. Several other attributes are defined
2128for functions on particular target systems. Other attributes,
2129including @code{section} are supported for variables declarations
2130(@pxref{Variable Attributes}) and for types (@pxref{Type Attributes}).
2131
2132GCC plugins may provide their own attributes.
2133
2134You may also specify attributes with @samp{__} preceding and following
2135each keyword. This allows you to use them in header files without
2136being concerned about a possible macro of the same name. For example,
2137you may use @code{__noreturn__} instead of @code{noreturn}.
2138
2139@xref{Attribute Syntax}, for details of the exact syntax for using
2140attributes.
2141
2142@table @code
2143@c Keep this table alphabetized by attribute name. Treat _ as space.
2144
2145@item alias ("@var{target}")
2146@cindex @code{alias} attribute
2147The @code{alias} attribute causes the declaration to be emitted as an
2148alias for another symbol, which must be specified. For instance,
2149
2150@smallexample
2151void __f () @{ /* @r{Do something.} */; @}
2152void f () __attribute__ ((weak, alias ("__f")));
2153@end smallexample
2154
2155defines @samp{f} to be a weak alias for @samp{__f}. In C++, the
2156mangled name for the target must be used. It is an error if @samp{__f}
2157is not defined in the same translation unit.
2158
2159Not all target machines support this attribute.
2160
2161@item aligned (@var{alignment})
2162@cindex @code{aligned} attribute
2163This attribute specifies a minimum alignment for the function,
2164measured in bytes.
2165
2166You cannot use this attribute to decrease the alignment of a function,
2167only to increase it. However, when you explicitly specify a function
2168alignment this will override the effect of the
2169@option{-falign-functions} (@pxref{Optimize Options}) option for this
2170function.
2171
2172Note that the effectiveness of @code{aligned} attributes may be
2173limited by inherent limitations in your linker. On many systems, the
2174linker is only able to arrange for functions to be aligned up to a
2175certain maximum alignment. (For some linkers, the maximum supported
2176alignment may be very very small.) See your linker documentation for
2177further information.
2178
2179The @code{aligned} attribute can also be used for variables and fields
2180(@pxref{Variable Attributes}.)
2181
2182@item alloc_size
2183@cindex @code{alloc_size} attribute
2184The @code{alloc_size} attribute is used to tell the compiler that the
2185function return value points to memory, where the size is given by
2186one or two of the functions parameters. GCC uses this
2187information to improve the correctness of @code{__builtin_object_size}.
2188
2189The function parameter(s) denoting the allocated size are specified by
2190one or two integer arguments supplied to the attribute. The allocated size
2191is either the value of the single function argument specified or the product
2192of the two function arguments specified. Argument numbering starts at
2193one.
2194
2195For instance,
2196
2197@smallexample
2198void* my_calloc(size_t, size_t) __attribute__((alloc_size(1,2)))
2199void my_realloc(void*, size_t) __attribute__((alloc_size(2)))
2200@end smallexample
2201
2202declares that my_calloc will return memory of the size given by
2203the product of parameter 1 and 2 and that my_realloc will return memory
2204of the size given by parameter 2.
2205
2206@item always_inline
2207@cindex @code{always_inline} function attribute
2208Generally, functions are not inlined unless optimization is specified.
2209For functions declared inline, this attribute inlines the function even
2210if no optimization level was specified.
2211
2212@item gnu_inline
2213@cindex @code{gnu_inline} function attribute
2214This attribute should be used with a function which is also declared
2215with the @code{inline} keyword. It directs GCC to treat the function
2216as if it were defined in gnu90 mode even when compiling in C99 or
2217gnu99 mode.
2218
2219If the function is declared @code{extern}, then this definition of the
2220function is used only for inlining. In no case is the function
2221compiled as a standalone function, not even if you take its address
2222explicitly. Such an address becomes an external reference, as if you
2223had only declared the function, and had not defined it. This has
2224almost the effect of a macro. The way to use this is to put a
2225function definition in a header file with this attribute, and put
2226another copy of the function, without @code{extern}, in a library
2227file. The definition in the header file will cause most calls to the
2228function to be inlined. If any uses of the function remain, they will
2229refer to the single copy in the library. Note that the two
2230definitions of the functions need not be precisely the same, although
2231if they do not have the same effect your program may behave oddly.
2232
2233In C, if the function is neither @code{extern} nor @code{static}, then
2234the function is compiled as a standalone function, as well as being
2235inlined where possible.
2236
2237This is how GCC traditionally handled functions declared
2238@code{inline}. Since ISO C99 specifies a different semantics for
2239@code{inline}, this function attribute is provided as a transition
2240measure and as a useful feature in its own right. This attribute is
2241available in GCC 4.1.3 and later. It is available if either of the
2242preprocessor macros @code{__GNUC_GNU_INLINE__} or
2243@code{__GNUC_STDC_INLINE__} are defined. @xref{Inline,,An Inline
2244Function is As Fast As a Macro}.
2245
2246In C++, this attribute does not depend on @code{extern} in any way,
2247but it still requires the @code{inline} keyword to enable its special
2248behavior.
2249
2250@item artificial
2251@cindex @code{artificial} function attribute
2252This attribute is useful for small inline wrappers which if possible
2253should appear during debugging as a unit, depending on the debug
2254info format it will either mean marking the function as artificial
2255or using the caller location for all instructions within the inlined
2256body.
2257
2258@item bank_switch
2259@cindex interrupt handler functions
2260When added to an interrupt handler with the M32C port, causes the
2261prologue and epilogue to use bank switching to preserve the registers
2262rather than saving them on the stack.
2263
2264@item flatten
2265@cindex @code{flatten} function attribute
2266Generally, inlining into a function is limited. For a function marked with
2267this attribute, every call inside this function will be inlined, if possible.
2268Whether the function itself is considered for inlining depends on its size and
2269the current inlining parameters.
2270
2271@item error ("@var{message}")
2272@cindex @code{error} function attribute
2273If this attribute is used on a function declaration and a call to such a function
2274is not eliminated through dead code elimination or other optimizations, an error
2275which will include @var{message} will be diagnosed. This is useful
2276for compile time checking, especially together with @code{__builtin_constant_p}
2277and inline functions where checking the inline function arguments is not
2278possible through @code{extern char [(condition) ? 1 : -1];} tricks.
2279While it is possible to leave the function undefined and thus invoke
2280a link failure, when using this attribute the problem will be diagnosed
2281earlier and with exact location of the call even in presence of inline
2282functions or when not emitting debugging information.
2283
2284@item warning ("@var{message}")
2285@cindex @code{warning} function attribute
2286If this attribute is used on a function declaration and a call to such a function
2287is not eliminated through dead code elimination or other optimizations, a warning
2288which will include @var{message} will be diagnosed. This is useful
2289for compile time checking, especially together with @code{__builtin_constant_p}
2290and inline functions. While it is possible to define the function with
2291a message in @code{.gnu.warning*} section, when using this attribute the problem
2292will be diagnosed earlier and with exact location of the call even in presence
2293of inline functions or when not emitting debugging information.
2294
2295@item cdecl
2296@cindex functions that do pop the argument stack on the 386
2297@opindex mrtd
2298On the Intel 386, the @code{cdecl} attribute causes the compiler to
2299assume that the calling function will pop off the stack space used to
2300pass arguments. This is
2301useful to override the effects of the @option{-mrtd} switch.
2302
2303@item const
2304@cindex @code{const} function attribute
2305Many functions do not examine any values except their arguments, and
2306have no effects except the return value. Basically this is just slightly
2307more strict class than the @code{pure} attribute below, since function is not
2308allowed to read global memory.
2309
2310@cindex pointer arguments
2311Note that a function that has pointer arguments and examines the data
2312pointed to must @emph{not} be declared @code{const}. Likewise, a
2313function that calls a non-@code{const} function usually must not be
2314@code{const}. It does not make sense for a @code{const} function to
2315return @code{void}.
2316
2317The attribute @code{const} is not implemented in GCC versions earlier
2318than 2.5. An alternative way to declare that a function has no side
2319effects, which works in the current version and in some older versions,
2320is as follows:
2321
2322@smallexample
2323typedef int intfn ();
2324
2325extern const intfn square;
2326@end smallexample
2327
2328This approach does not work in GNU C++ from 2.6.0 on, since the language
2329specifies that the @samp{const} must be attached to the return value.
2330
2331@item constructor
2332@itemx destructor
2333@itemx constructor (@var{priority})
2334@itemx destructor (@var{priority})
2335@cindex @code{constructor} function attribute
2336@cindex @code{destructor} function attribute
2337The @code{constructor} attribute causes the function to be called
2338automatically before execution enters @code{main ()}. Similarly, the
2339@code{destructor} attribute causes the function to be called
2340automatically after @code{main ()} has completed or @code{exit ()} has
2341been called. Functions with these attributes are useful for
2342initializing data that will be used implicitly during the execution of
2343the program.
2344
2345You may provide an optional integer priority to control the order in
2346which constructor and destructor functions are run. A constructor
2347with a smaller priority number runs before a constructor with a larger
2348priority number; the opposite relationship holds for destructors. So,
2349if you have a constructor that allocates a resource and a destructor
2350that deallocates the same resource, both functions typically have the
2351same priority. The priorities for constructor and destructor
2352functions are the same as those specified for namespace-scope C++
2353objects (@pxref{C++ Attributes}).
2354
2355These attributes are not currently implemented for Objective-C@.
2356
2357@item deprecated
2358@itemx deprecated (@var{msg})
2359@cindex @code{deprecated} attribute.
2360The @code{deprecated} attribute results in a warning if the function
2361is used anywhere in the source file. This is useful when identifying
2362functions that are expected to be removed in a future version of a
2363program. The warning also includes the location of the declaration
2364of the deprecated function, to enable users to easily find further
2365information about why the function is deprecated, or what they should
2366do instead. Note that the warnings only occurs for uses:
2367
2368@smallexample
2369int old_fn () __attribute__ ((deprecated));
2370int old_fn ();
2371int (*fn_ptr)() = old_fn;
2372@end smallexample
2373
2374results in a warning on line 3 but not line 2. The optional msg
2375argument, which must be a string, will be printed in the warning if
2376present.
2377
2378The @code{deprecated} attribute can also be used for variables and
2379types (@pxref{Variable Attributes}, @pxref{Type Attributes}.)
2380
2381@item disinterrupt
2382@cindex @code{disinterrupt} attribute
2383On Epiphany and MeP targets, this attribute causes the compiler to emit
2384instructions to disable interrupts for the duration of the given
2385function.
2386
2387@item dllexport
2388@cindex @code{__declspec(dllexport)}
2389On Microsoft Windows targets and Symbian OS targets the
2390@code{dllexport} attribute causes the compiler to provide a global
2391pointer to a pointer in a DLL, so that it can be referenced with the
2392@code{dllimport} attribute. On Microsoft Windows targets, the pointer
2393name is formed by combining @code{_imp__} and the function or variable
2394name.
2395
2396You can use @code{__declspec(dllexport)} as a synonym for
2397@code{__attribute__ ((dllexport))} for compatibility with other
2398compilers.
2399
2400On systems that support the @code{visibility} attribute, this
2401attribute also implies ``default'' visibility. It is an error to
2402explicitly specify any other visibility.
2403
2404In previous versions of GCC, the @code{dllexport} attribute was ignored
2405for inlined functions, unless the @option{-fkeep-inline-functions} flag
2406had been used. The default behaviour now is to emit all dllexported
2407inline functions; however, this can cause object file-size bloat, in
2408which case the old behaviour can be restored by using
2409@option{-fno-keep-inline-dllexport}.
2410
2411The attribute is also ignored for undefined symbols.
2412
2413When applied to C++ classes, the attribute marks defined non-inlined
2414member functions and static data members as exports. Static consts
2415initialized in-class are not marked unless they are also defined
2416out-of-class.
2417
2418For Microsoft Windows targets there are alternative methods for
2419including the symbol in the DLL's export table such as using a
2420@file{.def} file with an @code{EXPORTS} section or, with GNU ld, using
2421the @option{--export-all} linker flag.
2422
2423@item dllimport
2424@cindex @code{__declspec(dllimport)}
2425On Microsoft Windows and Symbian OS targets, the @code{dllimport}
2426attribute causes the compiler to reference a function or variable via
2427a global pointer to a pointer that is set up by the DLL exporting the
2428symbol. The attribute implies @code{extern}. On Microsoft Windows
2429targets, the pointer name is formed by combining @code{_imp__} and the
2430function or variable name.
2431
2432You can use @code{__declspec(dllimport)} as a synonym for
2433@code{__attribute__ ((dllimport))} for compatibility with other
2434compilers.
2435
2436On systems that support the @code{visibility} attribute, this
2437attribute also implies ``default'' visibility. It is an error to
2438explicitly specify any other visibility.
2439
2440Currently, the attribute is ignored for inlined functions. If the
2441attribute is applied to a symbol @emph{definition}, an error is reported.
2442If a symbol previously declared @code{dllimport} is later defined, the
2443attribute is ignored in subsequent references, and a warning is emitted.
2444The attribute is also overridden by a subsequent declaration as
2445@code{dllexport}.
2446
2447When applied to C++ classes, the attribute marks non-inlined
2448member functions and static data members as imports. However, the
2449attribute is ignored for virtual methods to allow creation of vtables
2450using thunks.
2451
2452On the SH Symbian OS target the @code{dllimport} attribute also has
2453another affect---it can cause the vtable and run-time type information
2454for a class to be exported. This happens when the class has a
2455dllimport'ed constructor or a non-inline, non-pure virtual function
2456and, for either of those two conditions, the class also has an inline
2457constructor or destructor and has a key function that is defined in
2458the current translation unit.
2459
2460For Microsoft Windows based targets the use of the @code{dllimport}
2461attribute on functions is not necessary, but provides a small
2462performance benefit by eliminating a thunk in the DLL@. The use of the
2463@code{dllimport} attribute on imported variables was required on older
2464versions of the GNU linker, but can now be avoided by passing the
2465@option{--enable-auto-import} switch to the GNU linker. As with
2466functions, using the attribute for a variable eliminates a thunk in
2467the DLL@.
2468
2469One drawback to using this attribute is that a pointer to a
2470@emph{variable} marked as @code{dllimport} cannot be used as a constant
2471address. However, a pointer to a @emph{function} with the
2472@code{dllimport} attribute can be used as a constant initializer; in
2473this case, the address of a stub function in the import lib is
2474referenced. On Microsoft Windows targets, the attribute can be disabled
2475for functions by setting the @option{-mnop-fun-dllimport} flag.
2476
2477@item eightbit_data
2478@cindex eight bit data on the H8/300, H8/300H, and H8S
2479Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specified
2480variable should be placed into the eight bit data section.
2481The compiler will generate more efficient code for certain operations
2482on data in the eight bit data area. Note the eight bit data area is limited to
2483256 bytes of data.
2484
2485You must use GAS and GLD from GNU binutils version 2.7 or later for
2486this attribute to work correctly.
2487
2488@item exception_handler
2489@cindex exception handler functions on the Blackfin processor
2490Use this attribute on the Blackfin to indicate that the specified function
2491is an exception handler. The compiler will generate function entry and
2492exit sequences suitable for use in an exception handler when this
2493attribute is present.
2494
2495@item externally_visible
2496@cindex @code{externally_visible} attribute.
2497This attribute, attached to a global variable or function, nullifies
2498the effect of the @option{-fwhole-program} command-line option, so the
2499object remains visible outside the current compilation unit. If @option{-fwhole-program} is used together with @option{-flto} and @command{gold} is used as the linker plugin, @code{externally_visible} attributes are automatically added to functions (not variable yet due to a current @command{gold} issue) that are accessed outside of LTO objects according to resolution file produced by @command{gold}. For other linkers that cannot generate resolution file, explicit @code{externally_visible} attributes are still necessary.
2500
2501@item far
2502@cindex functions which handle memory bank switching
2503On 68HC11 and 68HC12 the @code{far} attribute causes the compiler to
2504use a calling convention that takes care of switching memory banks when
2505entering and leaving a function. This calling convention is also the
2506default when using the @option{-mlong-calls} option.
2507
2508On 68HC12 the compiler will use the @code{call} and @code{rtc} instructions
2509to call and return from a function.
2510
2511On 68HC11 the compiler will generate a sequence of instructions
2512to invoke a board-specific routine to switch the memory bank and call the
2513real function. The board-specific routine simulates a @code{call}.
2514At the end of a function, it will jump to a board-specific routine
2515instead of using @code{rts}. The board-specific return routine simulates
2516the @code{rtc}.
2517
2518On MeP targets this causes the compiler to use a calling convention
2519which assumes the called function is too far away for the built-in
2520addressing modes.
2521
2522@item fast_interrupt
2523@cindex interrupt handler functions
2524Use this attribute on the M32C and RX ports to indicate that the specified
2525function is a fast interrupt handler. This is just like the
2526@code{interrupt} attribute, except that @code{freit} is used to return
2527instead of @code{reit}.
2528
2529@item fastcall
2530@cindex functions that pop the argument stack on the 386
2531On the Intel 386, the @code{fastcall} attribute causes the compiler to
2532pass the first argument (if of integral type) in the register ECX and
2533the second argument (if of integral type) in the register EDX@. Subsequent
2534and other typed arguments are passed on the stack. The called function will
2535pop the arguments off the stack. If the number of arguments is variable all
2536arguments are pushed on the stack.
2537
2538@item thiscall
2539@cindex functions that pop the argument stack on the 386
2540On the Intel 386, the @code{thiscall} attribute causes the compiler to
2541pass the first argument (if of integral type) in the register ECX.
2542Subsequent and other typed arguments are passed on the stack. The called
2543function will pop the arguments off the stack.
2544If the number of arguments is variable all arguments are pushed on the
2545stack.
2546The @code{thiscall} attribute is intended for C++ non-static member functions.
2547As gcc extension this calling convention can be used for C-functions
2548and for static member methods.
2549
2550@item format (@var{archetype}, @var{string-index}, @var{first-to-check})
2551@cindex @code{format} function attribute
2552@opindex Wformat
2553The @code{format} attribute specifies that a function takes @code{printf},
2554@code{scanf}, @code{strftime} or @code{strfmon} style arguments which
2555should be type-checked against a format string. For example, the
2556declaration:
2557
2558@smallexample
2559extern int
2560my_printf (void *my_object, const char *my_format, ...)
2561 __attribute__ ((format (printf, 2, 3)));
2562@end smallexample
2563
2564@noindent
2565causes the compiler to check the arguments in calls to @code{my_printf}
2566for consistency with the @code{printf} style format string argument
2567@code{my_format}.
2568
2569The parameter @var{archetype} determines how the format string is
2570interpreted, and should be @code{printf}, @code{scanf}, @code{strftime},
2571@code{gnu_printf}, @code{gnu_scanf}, @code{gnu_strftime} or
2572@code{strfmon}. (You can also use @code{__printf__},
2573@code{__scanf__}, @code{__strftime__} or @code{__strfmon__}.) On
2574MinGW targets, @code{ms_printf}, @code{ms_scanf}, and
2575@code{ms_strftime} are also present.
2576@var{archtype} values such as @code{printf} refer to the formats accepted
2577by the system's C run-time library, while @code{gnu_} values always refer
2578to the formats accepted by the GNU C Library. On Microsoft Windows
2579targets, @code{ms_} values refer to the formats accepted by the
2580@file{msvcrt.dll} library.
2581The parameter @var{string-index}
2582specifies which argument is the format string argument (starting
2583from 1), while @var{first-to-check} is the number of the first
2584argument to check against the format string. For functions
2585where the arguments are not available to be checked (such as
2586@code{vprintf}), specify the third parameter as zero. In this case the
2587compiler only checks the format string for consistency. For
2588@code{strftime} formats, the third parameter is required to be zero.
2589Since non-static C++ methods have an implicit @code{this} argument, the
2590arguments of such methods should be counted from two, not one, when
2591giving values for @var{string-index} and @var{first-to-check}.
2592
2593In the example above, the format string (@code{my_format}) is the second
2594argument of the function @code{my_print}, and the arguments to check
2595start with the third argument, so the correct parameters for the format
2596attribute are 2 and 3.
2597
2598@opindex ffreestanding
2599@opindex fno-builtin
2600The @code{format} attribute allows you to identify your own functions
2601which take format strings as arguments, so that GCC can check the
2602calls to these functions for errors. The compiler always (unless
2603@option{-ffreestanding} or @option{-fno-builtin} is used) checks formats
2604for the standard library functions @code{printf}, @code{fprintf},
2605@code{sprintf}, @code{scanf}, @code{fscanf}, @code{sscanf}, @code{strftime},
2606@code{vprintf}, @code{vfprintf} and @code{vsprintf} whenever such
2607warnings are requested (using @option{-Wformat}), so there is no need to
2608modify the header file @file{stdio.h}. In C99 mode, the functions
2609@code{snprintf}, @code{vsnprintf}, @code{vscanf}, @code{vfscanf} and
2610@code{vsscanf} are also checked. Except in strictly conforming C
2611standard modes, the X/Open function @code{strfmon} is also checked as
2612are @code{printf_unlocked} and @code{fprintf_unlocked}.
2613@xref{C Dialect Options,,Options Controlling C Dialect}.
2614
2615For Objective-C dialects, @code{NSString} (or @code{__NSString__}) is
2616recognized in the same context. Declarations including these format attributes
2617will be parsed for correct syntax, however the result of checking of such format
2618strings is not yet defined, and will not be carried out by this version of the
2619compiler.
2620
2621The target may also provide additional types of format checks.
2622@xref{Target Format Checks,,Format Checks Specific to Particular
2623Target Machines}.
2624
2625@item format_arg (@var{string-index})
2626@cindex @code{format_arg} function attribute
2627@opindex Wformat-nonliteral
2628The @code{format_arg} attribute specifies that a function takes a format
2629string for a @code{printf}, @code{scanf}, @code{strftime} or
2630@code{strfmon} style function and modifies it (for example, to translate
2631it into another language), so the result can be passed to a
2632@code{printf}, @code{scanf}, @code{strftime} or @code{strfmon} style
2633function (with the remaining arguments to the format function the same
2634as they would have been for the unmodified string). For example, the
2635declaration:
2636
2637@smallexample
2638extern char *
2639my_dgettext (char *my_domain, const char *my_format)
2640 __attribute__ ((format_arg (2)));
2641@end smallexample
2642
2643@noindent
2644causes the compiler to check the arguments in calls to a @code{printf},
2645@code{scanf}, @code{strftime} or @code{strfmon} type function, whose
2646format string argument is a call to the @code{my_dgettext} function, for
2647consistency with the format string argument @code{my_format}. If the
2648@code{format_arg} attribute had not been specified, all the compiler
2649could tell in such calls to format functions would be that the format
2650string argument is not constant; this would generate a warning when
2651@option{-Wformat-nonliteral} is used, but the calls could not be checked
2652without the attribute.
2653
2654The parameter @var{string-index} specifies which argument is the format
2655string argument (starting from one). Since non-static C++ methods have
2656an implicit @code{this} argument, the arguments of such methods should
2657be counted from two.
2658
2659The @code{format-arg} attribute allows you to identify your own
2660functions which modify format strings, so that GCC can check the
2661calls to @code{printf}, @code{scanf}, @code{strftime} or @code{strfmon}
2662type function whose operands are a call to one of your own function.
2663The compiler always treats @code{gettext}, @code{dgettext}, and
2664@code{dcgettext} in this manner except when strict ISO C support is
2665requested by @option{-ansi} or an appropriate @option{-std} option, or
2666@option{-ffreestanding} or @option{-fno-builtin}
2667is used. @xref{C Dialect Options,,Options
2668Controlling C Dialect}.
2669
2670For Objective-C dialects, the @code{format-arg} attribute may refer to an
2671@code{NSString} reference for compatibility with the @code{format} attribute
2672above.
2673
2674The target may also allow additional types in @code{format-arg} attributes.
2675@xref{Target Format Checks,,Format Checks Specific to Particular
2676Target Machines}.
2677
2678@item function_vector
2679@cindex calling functions through the function vector on H8/300, M16C, M32C and SH2A processors
2680Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specified
2681function should be called through the function vector. Calling a
2682function through the function vector will reduce code size, however;
2683the function vector has a limited size (maximum 128 entries on the H8/300
2684and 64 entries on the H8/300H and H8S) and shares space with the interrupt vector.
2685
2686In SH2A target, this attribute declares a function to be called using the
2687TBR relative addressing mode. The argument to this attribute is the entry
2688number of the same function in a vector table containing all the TBR
2689relative addressable functions. For the successful jump, register TBR
2690should contain the start address of this TBR relative vector table.
2691In the startup routine of the user application, user needs to care of this
2692TBR register initialization. The TBR relative vector table can have at
2693max 256 function entries. The jumps to these functions will be generated
2694using a SH2A specific, non delayed branch instruction JSR/N @@(disp8,TBR).
2695You must use GAS and GLD from GNU binutils version 2.7 or later for
2696this attribute to work correctly.
2697
2698Please refer the example of M16C target, to see the use of this
2699attribute while declaring a function,
2700
2701In an application, for a function being called once, this attribute will
2702save at least 8 bytes of code; and if other successive calls are being
2703made to the same function, it will save 2 bytes of code per each of these
2704calls.
2705
2706On M16C/M32C targets, the @code{function_vector} attribute declares a
2707special page subroutine call function. Use of this attribute reduces
2708the code size by 2 bytes for each call generated to the
2709subroutine. The argument to the attribute is the vector number entry
2710from the special page vector table which contains the 16 low-order
2711bits of the subroutine's entry address. Each vector table has special
2712page number (18 to 255) which are used in @code{jsrs} instruction.
2713Jump addresses of the routines are generated by adding 0x0F0000 (in
2714case of M16C targets) or 0xFF0000 (in case of M32C targets), to the 2
2715byte addresses set in the vector table. Therefore you need to ensure
2716that all the special page vector routines should get mapped within the
2717address range 0x0F0000 to 0x0FFFFF (for M16C) and 0xFF0000 to 0xFFFFFF
2718(for M32C).
2719
2720In the following example 2 bytes will be saved for each call to
2721function @code{foo}.
2722
2723@smallexample
2724void foo (void) __attribute__((function_vector(0x18)));
2725void foo (void)
2726@{
2727@}
2728
2729void bar (void)
2730@{
2731 foo();
2732@}
2733@end smallexample
2734
2735If functions are defined in one file and are called in another file,
2736then be sure to write this declaration in both files.
2737
2738This attribute is ignored for R8C target.
2739
2740@item ifunc ("@var{resolver}")
2741@cindex @code{ifunc} attribute
2742The @code{ifunc} attribute is used to mark a function as an indirect
2743function using the STT_GNU_IFUNC symbol type extension to the ELF
2744standard. This allows the resolution of the symbol value to be
2745determined dynamically at load time, and an optimized version of the
2746routine can be selected for the particular processor or other system
2747characteristics determined then. To use this attribute, first define
2748the implementation functions available, and a resolver function that
2749returns a pointer to the selected implementation function. The
2750implementation functions' declarations must match the API of the
2751function being implemented, the resolver's declaration is be a
2752function returning pointer to void function returning void:
2753
2754@smallexample
2755void *my_memcpy (void *dst, const void *src, size_t len)
2756@{
2757 @dots{}
2758@}
2759
2760static void (*resolve_memcpy (void)) (void)
2761@{
2762 return my_memcpy; // we'll just always select this routine
2763@}
2764@end smallexample
2765
2766The exported header file declaring the function the user calls would
2767contain:
2768
2769@smallexample
2770extern void *memcpy (void *, const void *, size_t);
2771@end smallexample
2772
2773allowing the user to call this as a regular function, unaware of the
2774implementation. Finally, the indirect function needs to be defined in
2775the same translation unit as the resolver function:
2776
2777@smallexample
2778void *memcpy (void *, const void *, size_t)
2779 __attribute__ ((ifunc ("resolve_memcpy")));
2780@end smallexample
2781
2782Indirect functions cannot be weak, and require a recent binutils (at
2783least version 2.20.1), and GNU C library (at least version 2.11.1).
2784
2785@item interrupt
2786@cindex interrupt handler functions
2787Use this attribute on the ARM, AVR, CR16, Epiphany, M32C, M32R/D, m68k, MeP, MIPS,
2788RL78, RX and Xstormy16 ports to indicate that the specified function is an
2789interrupt handler. The compiler will generate function entry and exit
2790sequences suitable for use in an interrupt handler when this attribute
2791is present. With Epiphany targets it may also generate a special section with
2792code to initialize the interrupt vector table.
2793
2794Note, interrupt handlers for the Blackfin, H8/300, H8/300H, H8S, MicroBlaze,
2795and SH processors can be specified via the @code{interrupt_handler} attribute.
2796
2797Note, on the AVR, the hardware globally disables interrupts when an
2798interrupt is executed. The first instruction of an interrupt handler
2799declared with this attribute will be a @code{SEI} instruction to
2800re-enable interrupts. See also the @code{signal} function attribute
2801that does not insert a @code{SEI} instuction. If both @code{signal} and
2802@code{interrupt} are specified for the same function, @code{signal}
2803will be silently ignored.
2804
2805Note, for the ARM, you can specify the kind of interrupt to be handled by
2806adding an optional parameter to the interrupt attribute like this:
2807
2808@smallexample
2809void f () __attribute__ ((interrupt ("IRQ")));
2810@end smallexample
2811
2812Permissible values for this parameter are: IRQ, FIQ, SWI, ABORT and UNDEF@.
2813
2814On ARMv7-M the interrupt type is ignored, and the attribute means the function
2815may be called with a word aligned stack pointer.
2816
2817On Epiphany targets one or more optional parameters can be added like this:
2818
2819@smallexample
2820void __attribute__ ((interrupt ("dma0, dma1"))) universal_dma_handler ();
2821@end smallexample
2822
2823Permissible values for these parameters are: @w{@code{reset}},
2824@w{@code{software_exception}}, @w{@code{page_miss}},
2825@w{@code{timer0}}, @w{@code{timer1}}, @w{@code{message}},
2826@w{@code{dma0}}, @w{@code{dma1}}, @w{@code{wand}} and @w{@code{swi}}.
2827Multiple parameters indicate that multiple entries in the interrupt
2828vector table should be initialized for this function, i.e. for each
2829parameter @w{@var{name}}, a jump to the function will be emitted in
2830the section @w{ivt_entry_@var{name}}. The parameter(s) may be omitted
2831entirely, in which case no interrupt vector table entry will be provided.
2832
2833Note, on Epiphany targets, interrupts are enabled inside the function
2834unless the @code{disinterrupt} attribute is also specified.
2835
2836On Epiphany targets, you can also use the following attribute to
2837modify the behavior of an interrupt handler:
2838@table @code
2839@item forwarder_section
2840@cindex @code{forwarder_section} attribute
2841The interrupt handler may be in external memory which cannot be
2842reached by a branch instruction, so generate a local memory trampoline
2843to transfer control. The single parameter identifies the section where
2844the trampoline will be placed.
2845@end table
2846
2847The following examples are all valid uses of these attributes on
2848Epiphany targets:
2849@smallexample
2850void __attribute__ ((interrupt)) universal_handler ();
2851void __attribute__ ((interrupt ("dma1"))) dma1_handler ();
2852void __attribute__ ((interrupt ("dma0, dma1"))) universal_dma_handler ();
2853void __attribute__ ((interrupt ("timer0"), disinterrupt))
2854 fast_timer_handler ();
2855void __attribute__ ((interrupt ("dma0, dma1"), forwarder_section ("tramp")))
2856 external_dma_handler ();
2857@end smallexample
2858
2859On MIPS targets, you can use the following attributes to modify the behavior
2860of an interrupt handler:
2861@table @code
2862@item use_shadow_register_set
2863@cindex @code{use_shadow_register_set} attribute
2864Assume that the handler uses a shadow register set, instead of
2865the main general-purpose registers.
2866
2867@item keep_interrupts_masked
2868@cindex @code{keep_interrupts_masked} attribute
2869Keep interrupts masked for the whole function. Without this attribute,
2870GCC tries to reenable interrupts for as much of the function as it can.
2871
2872@item use_debug_exception_return
2873@cindex @code{use_debug_exception_return} attribute
2874Return using the @code{deret} instruction. Interrupt handlers that don't
2875have this attribute return using @code{eret} instead.
2876@end table
2877
2878You can use any combination of these attributes, as shown below:
2879@smallexample
2880void __attribute__ ((interrupt)) v0 ();
2881void __attribute__ ((interrupt, use_shadow_register_set)) v1 ();
2882void __attribute__ ((interrupt, keep_interrupts_masked)) v2 ();
2883void __attribute__ ((interrupt, use_debug_exception_return)) v3 ();
2884void __attribute__ ((interrupt, use_shadow_register_set,
2885 keep_interrupts_masked)) v4 ();
2886void __attribute__ ((interrupt, use_shadow_register_set,
2887 use_debug_exception_return)) v5 ();
2888void __attribute__ ((interrupt, keep_interrupts_masked,
2889 use_debug_exception_return)) v6 ();
2890void __attribute__ ((interrupt, use_shadow_register_set,
2891 keep_interrupts_masked,
2892 use_debug_exception_return)) v7 ();
2893@end smallexample
2894
2895On RL78, use @code{brk_interrupt} instead of @code{interrupt} for
2896handlers intended to be used with the @code{BRK} opcode (i.e. those
2897that must end with @code{RETB} instead of @code{RETI}).
2898
2899@item interrupt_handler
2900@cindex interrupt handler functions on the Blackfin, m68k, H8/300 and SH processors
2901Use this attribute on the Blackfin, m68k, H8/300, H8/300H, H8S, and SH to
2902indicate that the specified function is an interrupt handler. The compiler
2903will generate function entry and exit sequences suitable for use in an
2904interrupt handler when this attribute is present.
2905
2906@item interrupt_thread
2907@cindex interrupt thread functions on fido
2908Use this attribute on fido, a subarchitecture of the m68k, to indicate
2909that the specified function is an interrupt handler that is designed
2910to run as a thread. The compiler omits generate prologue/epilogue
2911sequences and replaces the return instruction with a @code{sleep}
2912instruction. This attribute is available only on fido.
2913
2914@item isr
2915@cindex interrupt service routines on ARM
2916Use this attribute on ARM to write Interrupt Service Routines. This is an
2917alias to the @code{interrupt} attribute above.
2918
2919@item kspisusp
2920@cindex User stack pointer in interrupts on the Blackfin
2921When used together with @code{interrupt_handler}, @code{exception_handler}
2922or @code{nmi_handler}, code will be generated to load the stack pointer
2923from the USP register in the function prologue.
2924
2925@item l1_text
2926@cindex @code{l1_text} function attribute
2927This attribute specifies a function to be placed into L1 Instruction
2928SRAM@. The function will be put into a specific section named @code{.l1.text}.
2929With @option{-mfdpic}, function calls with a such function as the callee
2930or caller will use inlined PLT.
2931
2932@item l2
2933@cindex @code{l2} function attribute
2934On the Blackfin, this attribute specifies a function to be placed into L2
2935SRAM. The function will be put into a specific section named
2936@code{.l1.text}. With @option{-mfdpic}, callers of such functions will use
2937an inlined PLT.
2938
2939@item leaf
2940@cindex @code{leaf} function attribute
2941Calls to external functions with this attribute must return to the current
2942compilation unit only by return or by exception handling. In particular, leaf
2943functions are not allowed to call callback function passed to it from the current
2944compilation unit or directly call functions exported by the unit or longjmp
2945into the unit. Leaf function might still call functions from other compilation
2946units and thus they are not necessarily leaf in the sense that they contain no
2947function calls at all.
2948
2949The attribute is intended for library functions to improve dataflow analysis.
2950The compiler takes the hint that any data not escaping the current compilation unit can
2951not be used or modified by the leaf function. For example, the @code{sin} function
2952is a leaf function, but @code{qsort} is not.
2953
2954Note that leaf functions might invoke signals and signal handlers might be
2955defined in the current compilation unit and use static variables. The only
2956compliant way to write such a signal handler is to declare such variables
2957@code{volatile}.
2958
2959The attribute has no effect on functions defined within the current compilation
2960unit. This is to allow easy merging of multiple compilation units into one,
2961for example, by using the link time optimization. For this reason the
2962attribute is not allowed on types to annotate indirect calls.
2963
2964@item long_call/short_call
2965@cindex indirect calls on ARM
2966This attribute specifies how a particular function is called on
2967ARM and Epiphany. Both attributes override the
2968@option{-mlong-calls} (@pxref{ARM Options})
2969command-line switch and @code{#pragma long_calls} settings. The
2970@code{long_call} attribute indicates that the function might be far
2971away from the call site and require a different (more expensive)
2972calling sequence. The @code{short_call} attribute always places
2973the offset to the function from the call site into the @samp{BL}
2974instruction directly.
2975
2976@item longcall/shortcall
2977@cindex functions called via pointer on the RS/6000 and PowerPC
2978On the Blackfin, RS/6000 and PowerPC, the @code{longcall} attribute
2979indicates that the function might be far away from the call site and
2980require a different (more expensive) calling sequence. The
2981@code{shortcall} attribute indicates that the function is always close
2982enough for the shorter calling sequence to be used. These attributes
2983override both the @option{-mlongcall} switch and, on the RS/6000 and
2984PowerPC, the @code{#pragma longcall} setting.
2985
2986@xref{RS/6000 and PowerPC Options}, for more information on whether long
2987calls are necessary.
2988
2989@item long_call/near/far
2990@cindex indirect calls on MIPS
2991These attributes specify how a particular function is called on MIPS@.
2992The attributes override the @option{-mlong-calls} (@pxref{MIPS Options})
2993command-line switch. The @code{long_call} and @code{far} attributes are
2994synonyms, and cause the compiler to always call
2995the function by first loading its address into a register, and then using
2996the contents of that register. The @code{near} attribute has the opposite
2997effect; it specifies that non-PIC calls should be made using the more
2998efficient @code{jal} instruction.
2999
3000@item malloc
3001@cindex @code{malloc} attribute
3002The @code{malloc} attribute is used to tell the compiler that a function
3003may be treated as if any non-@code{NULL} pointer it returns cannot
3004alias any other pointer valid when the function returns and that the memory
3005has undefined content.
3006This will often improve optimization.
3007Standard functions with this property include @code{malloc} and
3008@code{calloc}. @code{realloc}-like functions do not have this
3009property as the memory pointed to does not have undefined content.
3010
3011@item mips16/nomips16
3012@cindex @code{mips16} attribute
3013@cindex @code{nomips16} attribute
3014
3015On MIPS targets, you can use the @code{mips16} and @code{nomips16}
3016function attributes to locally select or turn off MIPS16 code generation.
3017A function with the @code{mips16} attribute is emitted as MIPS16 code,
3018while MIPS16 code generation is disabled for functions with the
3019@code{nomips16} attribute. These attributes override the
3020@option{-mips16} and @option{-mno-mips16} options on the command line
3021(@pxref{MIPS Options}).
3022
3023When compiling files containing mixed MIPS16 and non-MIPS16 code, the
3024preprocessor symbol @code{__mips16} reflects the setting on the command line,
3025not that within individual functions. Mixed MIPS16 and non-MIPS16 code
3026may interact badly with some GCC extensions such as @code{__builtin_apply}
3027(@pxref{Constructing Calls}).
3028
3029@item model (@var{model-name})
3030@cindex function addressability on the M32R/D
3031@cindex variable addressability on the IA-64
3032
3033On the M32R/D, use this attribute to set the addressability of an
3034object, and of the code generated for a function. The identifier
3035@var{model-name} is one of @code{small}, @code{medium}, or
3036@code{large}, representing each of the code models.
3037
3038Small model objects live in the lower 16MB of memory (so that their
3039addresses can be loaded with the @code{ld24} instruction), and are
3040callable with the @code{bl} instruction.
3041
3042Medium model objects may live anywhere in the 32-bit address space (the
3043compiler will generate @code{seth/add3} instructions to load their addresses),
3044and are callable with the @code{bl} instruction.
3045
3046Large model objects may live anywhere in the 32-bit address space (the
3047compiler will generate @code{seth/add3} instructions to load their addresses),
3048and may not be reachable with the @code{bl} instruction (the compiler will
3049generate the much slower @code{seth/add3/jl} instruction sequence).
3050
3051On IA-64, use this attribute to set the addressability of an object.
3052At present, the only supported identifier for @var{model-name} is
3053@code{small}, indicating addressability via ``small'' (22-bit)
3054addresses (so that their addresses can be loaded with the @code{addl}
3055instruction). Caveat: such addressing is by definition not position
3056independent and hence this attribute must not be used for objects
3057defined by shared libraries.
3058
3059@item ms_abi/sysv_abi
3060@cindex @code{ms_abi} attribute
3061@cindex @code{sysv_abi} attribute
3062
3063On 32-bit and 64-bit (i?86|x86_64)-*-* targets, you can use an ABI attribute
3064to indicate which calling convention should be used for a function. The
3065@code{ms_abi} attribute tells the compiler to use the Microsoft ABI,
3066while the @code{sysv_abi} attribute tells the compiler to use the ABI
3067used on GNU/Linux and other systems. The default is to use the Microsoft ABI
3068when targeting Windows. On all other systems, the default is the x86/AMD ABI.
3069
3070Note, the @code{ms_abi} attribute for Windows 64-bit targets currently
3071requires the @option{-maccumulate-outgoing-args} option.
3072
3073@item callee_pop_aggregate_return (@var{number})
3074@cindex @code{callee_pop_aggregate_return} attribute
3075
3076On 32-bit i?86-*-* targets, you can control by those attribute for
3077aggregate return in memory, if the caller is responsible to pop the hidden
3078pointer together with the rest of the arguments - @var{number} equal to
3079zero -, or if the callee is responsible to pop hidden pointer - @var{number}
3080equal to one. The default i386 ABI assumes that the callee pops the
3081stack for hidden pointer.
3082
3083Note, that on 32-bit i386 Windows targets the compiler assumes that the
3084caller pops the stack for hidden pointer.
3085
3086@item ms_hook_prologue
3087@cindex @code{ms_hook_prologue} attribute
3088
3089On 32 bit i[34567]86-*-* targets and 64 bit x86_64-*-* targets, you can use
3090this function attribute to make gcc generate the "hot-patching" function
3091prologue used in Win32 API functions in Microsoft Windows XP Service Pack 2
3092and newer.
3093
3094@item naked
3095@cindex function without a prologue/epilogue code
3096Use this attribute on the ARM, AVR, MCORE, RX and SPU ports to indicate that
3097the specified function does not need prologue/epilogue sequences generated by
3098the compiler. It is up to the programmer to provide these sequences. The
3099only statements that can be safely included in naked functions are
3100@code{asm} statements that do not have operands. All other statements,
3101including declarations of local variables, @code{if} statements, and so
3102forth, should be avoided. Naked functions should be used to implement the
3103body of an assembly function, while allowing the compiler to construct
3104the requisite function declaration for the assembler.
3105
3106@item near
3107@cindex functions which do not handle memory bank switching on 68HC11/68HC12
3108On 68HC11 and 68HC12 the @code{near} attribute causes the compiler to
3109use the normal calling convention based on @code{jsr} and @code{rts}.
3110This attribute can be used to cancel the effect of the @option{-mlong-calls}
3111option.
3112
3113On MeP targets this attribute causes the compiler to assume the called
3114function is close enough to use the normal calling convention,
3115overriding the @code{-mtf} command line option.
3116
3117@item nesting
3118@cindex Allow nesting in an interrupt handler on the Blackfin processor.
3119Use this attribute together with @code{interrupt_handler},
3120@code{exception_handler} or @code{nmi_handler} to indicate that the function
3121entry code should enable nested interrupts or exceptions.
3122
3123@item nmi_handler
3124@cindex NMI handler functions on the Blackfin processor
3125Use this attribute on the Blackfin to indicate that the specified function
3126is an NMI handler. The compiler will generate function entry and
3127exit sequences suitable for use in an NMI handler when this
3128attribute is present.
3129
3130@item no_instrument_function
3131@cindex @code{no_instrument_function} function attribute
3132@opindex finstrument-functions
3133If @option{-finstrument-functions} is given, profiling function calls will
3134be generated at entry and exit of most user-compiled functions.
3135Functions with this attribute will not be so instrumented.
3136
3137@item no_split_stack
3138@cindex @code{no_split_stack} function attribute
3139@opindex fsplit-stack
3140If @option{-fsplit-stack} is given, functions will have a small
3141prologue which decides whether to split the stack. Functions with the
3142@code{no_split_stack} attribute will not have that prologue, and thus
3143may run with only a small amount of stack space available.
3144
3145@item noinline
3146@cindex @code{noinline} function attribute
3147This function attribute prevents a function from being considered for
3148inlining.
3149@c Don't enumerate the optimizations by name here; we try to be
3150@c future-compatible with this mechanism.
3151If the function does not have side-effects, there are optimizations
3152other than inlining that causes function calls to be optimized away,
3153although the function call is live. To keep such calls from being
3154optimized away, put
3155@smallexample
3156asm ("");
3157@end smallexample
3158(@pxref{Extended Asm}) in the called function, to serve as a special
3159side-effect.
3160
3161@item noclone
3162@cindex @code{noclone} function attribute
3163This function attribute prevents a function from being considered for
3164cloning - a mechanism which produces specialized copies of functions
3165and which is (currently) performed by interprocedural constant
3166propagation.
3167
3168@item nonnull (@var{arg-index}, @dots{})
3169@cindex @code{nonnull} function attribute
3170The @code{nonnull} attribute specifies that some function parameters should
3171be non-null pointers. For instance, the declaration:
3172
3173@smallexample
3174extern void *
3175my_memcpy (void *dest, const void *src, size_t len)
3176 __attribute__((nonnull (1, 2)));
3177@end smallexample
3178
3179@noindent
3180causes the compiler to check that, in calls to @code{my_memcpy},
3181arguments @var{dest} and @var{src} are non-null. If the compiler
3182determines that a null pointer is passed in an argument slot marked
3183as non-null, and the @option{-Wnonnull} option is enabled, a warning
3184is issued. The compiler may also choose to make optimizations based
3185on the knowledge that certain function arguments will not be null.
3186
3187If no argument index list is given to the @code{nonnull} attribute,
3188all pointer arguments are marked as non-null. To illustrate, the
3189following declaration is equivalent to the previous example:
3190
3191@smallexample
3192extern void *
3193my_memcpy (void *dest, const void *src, size_t len)
3194 __attribute__((nonnull));
3195@end smallexample
3196
3197@item noreturn
3198@cindex @code{noreturn} function attribute
3199A few standard library functions, such as @code{abort} and @code{exit},
3200cannot return. GCC knows this automatically. Some programs define
3201their own functions that never return. You can declare them
3202@code{noreturn} to tell the compiler this fact. For example,
3203
3204@smallexample
3205@group
3206void fatal () __attribute__ ((noreturn));
3207
3208void
3209fatal (/* @r{@dots{}} */)
3210@{
3211 /* @r{@dots{}} */ /* @r{Print error message.} */ /* @r{@dots{}} */
3212 exit (1);
3213@}
3214@end group
3215@end smallexample
3216
3217The @code{noreturn} keyword tells the compiler to assume that
3218@code{fatal} cannot return. It can then optimize without regard to what
3219would happen if @code{fatal} ever did return. This makes slightly
3220better code. More importantly, it helps avoid spurious warnings of
3221uninitialized variables.
3222
3223The @code{noreturn} keyword does not affect the exceptional path when that
3224applies: a @code{noreturn}-marked function may still return to the caller
3225by throwing an exception or calling @code{longjmp}.
3226
3227Do not assume that registers saved by the calling function are
3228restored before calling the @code{noreturn} function.
3229
3230It does not make sense for a @code{noreturn} function to have a return
3231type other than @code{void}.
3232
3233The attribute @code{noreturn} is not implemented in GCC versions
3234earlier than 2.5. An alternative way to declare that a function does
3235not return, which works in the current version and in some older
3236versions, is as follows:
3237
3238@smallexample
3239typedef void voidfn ();
3240
3241volatile voidfn fatal;
3242@end smallexample
3243
3244This approach does not work in GNU C++.
3245
3246@item nothrow
3247@cindex @code{nothrow} function attribute
3248The @code{nothrow} attribute is used to inform the compiler that a
3249function cannot throw an exception. For example, most functions in
3250the standard C library can be guaranteed not to throw an exception
3251with the notable exceptions of @code{qsort} and @code{bsearch} that
3252take function pointer arguments. The @code{nothrow} attribute is not
3253implemented in GCC versions earlier than 3.3.
3254
3255@item optimize
3256@cindex @code{optimize} function attribute
3257The @code{optimize} attribute is used to specify that a function is to
3258be compiled with different optimization options than specified on the
3259command line. Arguments can either be numbers or strings. Numbers
3260are assumed to be an optimization level. Strings that begin with
3261@code{O} are assumed to be an optimization option, while other options
3262are assumed to be used with a @code{-f} prefix. You can also use the
3263@samp{#pragma GCC optimize} pragma to set the optimization options
3264that affect more than one function.
3265@xref{Function Specific Option Pragmas}, for details about the
3266@samp{#pragma GCC optimize} pragma.
3267
3268This can be used for instance to have frequently executed functions
3269compiled with more aggressive optimization options that produce faster
3270and larger code, while other functions can be called with less
3271aggressive options.
3272
3273@item OS_main/OS_task
3274@cindex @code{OS_main} AVR function attribute
3275@cindex @code{OS_task} AVR function attribute
3276On AVR, functions with the @code{OS_main} or @code{OS_task} attribute
3277do not save/restore any call-saved register in their prologue/epilogue.
3278
3279The @code{OS_main} attribute can be used when there @emph{is
3280guarantee} that interrupts are disabled at the time when the function
3281is entered. This will save resources when the stack pointer has to be
3282changed to set up a frame for local variables.
3283
3284The @code{OS_task} attribute can be used when there is @emph{no
3285guarantee} that interrupts are disabled at that time when the function
3286is entered like for, e@.g@. task functions in a multi-threading operating
3287system. In that case, changing the stack pointer register will be
3288guarded by save/clear/restore of the global interrupt enable flag.
3289
3290The differences to the @code{naked} function attribute are:
3291@itemize @bullet
3292@item @code{naked} functions do not have a return instruction whereas
3293@code{OS_main} and @code{OS_task} functions will have a @code{RET} or
3294@code{RETI} return instruction.
3295@item @code{naked} functions do not set up a frame for local variables
3296or a frame pointer whereas @code{OS_main} and @code{OS_task} do this
3297as needed.
3298@end itemize
3299
3300@item pcs
3301@cindex @code{pcs} function attribute
3302
3303The @code{pcs} attribute can be used to control the calling convention
3304used for a function on ARM. The attribute takes an argument that specifies
3305the calling convention to use.
3306
3307When compiling using the AAPCS ABI (or a variant of that) then valid
3308values for the argument are @code{"aapcs"} and @code{"aapcs-vfp"}. In
3309order to use a variant other than @code{"aapcs"} then the compiler must
3310be permitted to use the appropriate co-processor registers (i.e., the
3311VFP registers must be available in order to use @code{"aapcs-vfp"}).
3312For example,
3313
3314@smallexample
3315/* Argument passed in r0, and result returned in r0+r1. */
3316double f2d (float) __attribute__((pcs("aapcs")));
3317@end smallexample
3318
3319Variadic functions always use the @code{"aapcs"} calling convention and
3320the compiler will reject attempts to specify an alternative.
3321
3322@item pure
3323@cindex @code{pure} function attribute
3324Many functions have no effects except the return value and their
3325return value depends only on the parameters and/or global variables.
3326Such a function can be subject
3327to common subexpression elimination and loop optimization just as an
3328arithmetic operator would be. These functions should be declared
3329with the attribute @code{pure}. For example,
3330
3331@smallexample
3332int square (int) __attribute__ ((pure));
3333@end smallexample
3334
3335@noindent
3336says that the hypothetical function @code{square} is safe to call
3337fewer times than the program says.
3338
3339Some of common examples of pure functions are @code{strlen} or @code{memcmp}.
3340Interesting non-pure functions are functions with infinite loops or those
3341depending on volatile memory or other system resource, that may change between
3342two consecutive calls (such as @code{feof} in a multithreading environment).
3343
3344The attribute @code{pure} is not implemented in GCC versions earlier
3345than 2.96.
3346
3347@item hot
3348@cindex @code{hot} function attribute
3349The @code{hot} attribute is used to inform the compiler that a function is a
3350hot spot of the compiled program. The function is optimized more aggressively
3351and on many target it is placed into special subsection of the text section so
3352all hot functions appears close together improving locality.
3353
3354When profile feedback is available, via @option{-fprofile-use}, hot functions
3355are automatically detected and this attribute is ignored.
3356
3357The @code{hot} attribute is not implemented in GCC versions earlier
3358than 4.3.
3359
3360@item cold
3361@cindex @code{cold} function attribute
3362The @code{cold} attribute is used to inform the compiler that a function is
3363unlikely executed. The function is optimized for size rather than speed and on
3364many targets it is placed into special subsection of the text section so all
3365cold functions appears close together improving code locality of non-cold parts
3366of program. The paths leading to call of cold functions within code are marked
3367as unlikely by the branch prediction mechanism. It is thus useful to mark
3368functions used to handle unlikely conditions, such as @code{perror}, as cold to
3369improve optimization of hot functions that do call marked functions in rare
3370occasions.
3371
3372When profile feedback is available, via @option{-fprofile-use}, hot functions
3373are automatically detected and this attribute is ignored.
3374
3375The @code{cold} attribute is not implemented in GCC versions earlier than 4.3.
3376
3377@item regparm (@var{number})
3378@cindex @code{regparm} attribute
3379@cindex functions that are passed arguments in registers on the 386
3380On the Intel 386, the @code{regparm} attribute causes the compiler to
3381pass arguments number one to @var{number} if they are of integral type
3382in registers EAX, EDX, and ECX instead of on the stack. Functions that
3383take a variable number of arguments will continue to be passed all of their
3384arguments on the stack.
3385
3386Beware that on some ELF systems this attribute is unsuitable for
3387global functions in shared libraries with lazy binding (which is the
3388default). Lazy binding will send the first call via resolving code in
3389the loader, which might assume EAX, EDX and ECX can be clobbered, as
3390per the standard calling conventions. Solaris 8 is affected by this.
3391GNU systems with GLIBC 2.1 or higher, and FreeBSD, are believed to be
3392safe since the loaders there save EAX, EDX and ECX. (Lazy binding can be
3393disabled with the linker or the loader if desired, to avoid the
3394problem.)
3395
3396@item sseregparm
3397@cindex @code{sseregparm} attribute
3398On the Intel 386 with SSE support, the @code{sseregparm} attribute
3399causes the compiler to pass up to 3 floating point arguments in
3400SSE registers instead of on the stack. Functions that take a
3401variable number of arguments will continue to pass all of their
3402floating point arguments on the stack.
3403
3404@item force_align_arg_pointer
3405@cindex @code{force_align_arg_pointer} attribute
3406On the Intel x86, the @code{force_align_arg_pointer} attribute may be
3407applied to individual function definitions, generating an alternate
3408prologue and epilogue that realigns the runtime stack if necessary.
3409This supports mixing legacy codes that run with a 4-byte aligned stack
3410with modern codes that keep a 16-byte stack for SSE compatibility.
3411
3412@item resbank
3413@cindex @code{resbank} attribute
3414On the SH2A target, this attribute enables the high-speed register
3415saving and restoration using a register bank for @code{interrupt_handler}
3416routines. Saving to the bank is performed automatically after the CPU
3417accepts an interrupt that uses a register bank.
3418
3419The nineteen 32-bit registers comprising general register R0 to R14,
3420control register GBR, and system registers MACH, MACL, and PR and the
3421vector table address offset are saved into a register bank. Register
3422banks are stacked in first-in last-out (FILO) sequence. Restoration
3423from the bank is executed by issuing a RESBANK instruction.
3424
3425@item returns_twice
3426@cindex @code{returns_twice} attribute
3427The @code{returns_twice} attribute tells the compiler that a function may
3428return more than one time. The compiler will ensure that all registers
3429are dead before calling such a function and will emit a warning about
3430the variables that may be clobbered after the second return from the
3431function. Examples of such functions are @code{setjmp} and @code{vfork}.
3432The @code{longjmp}-like counterpart of such function, if any, might need
3433to be marked with the @code{noreturn} attribute.
3434
3435@item saveall
3436@cindex save all registers on the Blackfin, H8/300, H8/300H, and H8S
3437Use this attribute on the Blackfin, H8/300, H8/300H, and H8S to indicate that
3438all registers except the stack pointer should be saved in the prologue
3439regardless of whether they are used or not.
3440
3441@item save_volatiles
3442@cindex save volatile registers on the MicroBlaze
3443Use this attribute on the MicroBlaze to indicate that the function is
3444an interrupt handler. All volatile registers (in addition to non-volatile
3445registers) will be saved in the function prologue. If the function is a leaf
3446function, only volatiles used by the function are saved. A normal function
3447return is generated instead of a return from interrupt.
3448
3449@item section ("@var{section-name}")
3450@cindex @code{section} function attribute
3451Normally, the compiler places the code it generates in the @code{text} section.
3452Sometimes, however, you need additional sections, or you need certain
3453particular functions to appear in special sections. The @code{section}
3454attribute specifies that a function lives in a particular section.
3455For example, the declaration:
3456
3457@smallexample
3458extern void foobar (void) __attribute__ ((section ("bar")));
3459@end smallexample
3460
3461@noindent
3462puts the function @code{foobar} in the @code{bar} section.
3463
3464Some file formats do not support arbitrary sections so the @code{section}
3465attribute is not available on all platforms.
3466If you need to map the entire contents of a module to a particular
3467section, consider using the facilities of the linker instead.
3468
3469@item sentinel
3470@cindex @code{sentinel} function attribute
3471This function attribute ensures that a parameter in a function call is
3472an explicit @code{NULL}. The attribute is only valid on variadic
3473functions. By default, the sentinel is located at position zero, the
3474last parameter of the function call. If an optional integer position
3475argument P is supplied to the attribute, the sentinel must be located at
3476position P counting backwards from the end of the argument list.
3477
3478@smallexample
3479__attribute__ ((sentinel))
3480is equivalent to
3481__attribute__ ((sentinel(0)))
3482@end smallexample
3483
3484The attribute is automatically set with a position of 0 for the built-in
3485functions @code{execl} and @code{execlp}. The built-in function
3486@code{execle} has the attribute set with a position of 1.
3487
3488A valid @code{NULL} in this context is defined as zero with any pointer
3489type. If your system defines the @code{NULL} macro with an integer type
3490then you need to add an explicit cast. GCC replaces @code{stddef.h}
3491with a copy that redefines NULL appropriately.
3492
3493The warnings for missing or incorrect sentinels are enabled with
3494@option{-Wformat}.
3495
3496@item short_call
3497See long_call/short_call.
3498
3499@item shortcall
3500See longcall/shortcall.
3501
3502@item signal
3503@cindex interrupt handler functions on the AVR processors
3504Use this attribute on the AVR to indicate that the specified
3505function is an interrupt handler. The compiler will generate function
3506entry and exit sequences suitable for use in an interrupt handler when this
3507attribute is present.
3508
3509See also the @code{interrupt} function attribute.
3510
3511The AVR hardware globally disables interrupts when an interrupt is executed.
3512Interrupt handler functions defined with the @code{signal} attribute
3513do not re-enable interrupts. It is save to enable interrupts in a
3514@code{signal} handler. This ``save'' only applies to the code
3515generated by the compiler and not to the IRQ-layout of the
3516application which is responsibility of the application.
3517
3518If both @code{signal} and @code{interrupt} are specified for the same
3519function, @code{signal} will be silently ignored.
3520
3521@item sp_switch
3522Use this attribute on the SH to indicate an @code{interrupt_handler}
3523function should switch to an alternate stack. It expects a string
3524argument that names a global variable holding the address of the
3525alternate stack.
3526
3527@smallexample
3528void *alt_stack;
3529void f () __attribute__ ((interrupt_handler,
3530 sp_switch ("alt_stack")));
3531@end smallexample
3532
3533@item stdcall
3534@cindex functions that pop the argument stack on the 386
3535On the Intel 386, the @code{stdcall} attribute causes the compiler to
3536assume that the called function will pop off the stack space used to
3537pass arguments, unless it takes a variable number of arguments.
3538
3539@item syscall_linkage
3540@cindex @code{syscall_linkage} attribute
3541This attribute is used to modify the IA64 calling convention by marking
3542all input registers as live at all function exits. This makes it possible
3543to restart a system call after an interrupt without having to save/restore
3544the input registers. This also prevents kernel data from leaking into
3545application code.
3546
3547@item target
3548@cindex @code{target} function attribute
3549The @code{target} attribute is used to specify that a function is to
3550be compiled with different target options than specified on the
3551command line. This can be used for instance to have functions
3552compiled with a different ISA (instruction set architecture) than the
3553default. You can also use the @samp{#pragma GCC target} pragma to set
3554more than one function to be compiled with specific target options.
3555@xref{Function Specific Option Pragmas}, for details about the
3556@samp{#pragma GCC target} pragma.
3557
3558For instance on a 386, you could compile one function with
3559@code{target("sse4.1,arch=core2")} and another with
3560@code{target("sse4a,arch=amdfam10")} that would be equivalent to
3561compiling the first function with @option{-msse4.1} and
3562@option{-march=core2} options, and the second function with
3563@option{-msse4a} and @option{-march=amdfam10} options. It is up to the
3564user to make sure that a function is only invoked on a machine that
3565supports the particular ISA it was compiled for (for example by using
3566@code{cpuid} on 386 to determine what feature bits and architecture
3567family are used).
3568
3569@smallexample
3570int core2_func (void) __attribute__ ((__target__ ("arch=core2")));
3571int sse3_func (void) __attribute__ ((__target__ ("sse3")));
3572@end smallexample
3573
3574On the 386, the following options are allowed:
3575
3576@table @samp
3577@item abm
3578@itemx no-abm
3579@cindex @code{target("abm")} attribute
3580Enable/disable the generation of the advanced bit instructions.
3581
3582@item aes
3583@itemx no-aes
3584@cindex @code{target("aes")} attribute
3585Enable/disable the generation of the AES instructions.
3586
3587@item mmx
3588@itemx no-mmx
3589@cindex @code{target("mmx")} attribute
3590Enable/disable the generation of the MMX instructions.
3591
3592@item pclmul
3593@itemx no-pclmul
3594@cindex @code{target("pclmul")} attribute
3595Enable/disable the generation of the PCLMUL instructions.
3596
3597@item popcnt
3598@itemx no-popcnt
3599@cindex @code{target("popcnt")} attribute
3600Enable/disable the generation of the POPCNT instruction.
3601
3602@item sse
3603@itemx no-sse
3604@cindex @code{target("sse")} attribute
3605Enable/disable the generation of the SSE instructions.
3606
3607@item sse2
3608@itemx no-sse2
3609@cindex @code{target("sse2")} attribute
3610Enable/disable the generation of the SSE2 instructions.
3611
3612@item sse3
3613@itemx no-sse3
3614@cindex @code{target("sse3")} attribute
3615Enable/disable the generation of the SSE3 instructions.
3616
3617@item sse4
3618@itemx no-sse4
3619@cindex @code{target("sse4")} attribute
3620Enable/disable the generation of the SSE4 instructions (both SSE4.1
3621and SSE4.2).
3622
3623@item sse4.1
3624@itemx no-sse4.1
3625@cindex @code{target("sse4.1")} attribute
3626Enable/disable the generation of the sse4.1 instructions.
3627
3628@item sse4.2
3629@itemx no-sse4.2
3630@cindex @code{target(&quo