|
|
1.1 root 1: @c Copyright (C) 1988, 1989, 1992 Free Software Foundation, Inc.
2: @c This is part of the GCC manual.
3: @c For copying conditions, see the file gcc.texi.
4:
1.1.1.3 ! root 5: @node Extensions
1.1 root 6: @chapter GNU Extensions to the C Language
7: @cindex extensions, C language
8: @cindex GNU extensions to the C language
9: @cindex C language extensions
10:
11: GNU C provides several language features not found in ANSI standard C.
12: (The @samp{-pedantic} option directs GNU CC to print a warning message if
13: any of these features is used.) To test for the availability of these
14: features in conditional compilation, check for a predefined macro
15: @code{__GNUC__}, which is always defined under GNU CC.
16:
17: @menu
18: * Statement Exprs:: Putting statements and declarations inside expressions.
19: * Local Labels:: Labels local to a statement-expression.
20: * Labels as Values:: Getting pointers to labels, and computed gotos.
21: * Nested Functions:: As in Algol and Pascal, lexical scoping of functions.
22: * Naming Types:: Giving a name to the type of some expression.
23: * Typeof:: @code{typeof}: referring to the type of an expression.
24: * Lvalues:: Using @samp{?:}, @samp{,} and casts in lvalues.
25: * Conditionals:: Omitting the middle operand of a @samp{?:} expression.
26: * Long Long:: Double-word integers---@code{long long int}.
27: * Zero Length:: Zero-length arrays.
28: * Variable Length:: Arrays whose length is computed at run time.
1.1.1.3 ! root 29: * Macro Varargs:: Macros with variable number of arguments.
1.1 root 30: * Subscripting:: Any array can be subscripted, even if not an lvalue.
31: * Pointer Arith:: Arithmetic on @code{void}-pointers and function pointers.
32: * Initializers:: Non-constant initializers.
33: * Constructors:: Constructor expressions give structures, unions
34: or arrays as values.
35: * Labeled Elements:: Labeling elements of initializers.
36: * Cast to Union:: Casting to union type from any member of the union.
37: * Case Ranges:: `case 1 ... 9' and such.
38: * Function Attributes:: Declaring that functions have no side effects,
39: or that they can never return.
1.1.1.3 ! root 40: * Function Prototypes:: Prototype declarations and old-style definitions.
1.1 root 41: * Dollar Signs:: Dollar sign is allowed in identifiers.
42: * Character Escapes:: @samp{\e} stands for the character @key{ESC}.
43: * Variable Attributes:: Specifying attributes of variables.
44: * Alignment:: Inquiring about the alignment of a type or variable.
45: * Inline:: Defining inline functions (as fast as macros).
46: * Extended Asm:: Assembler instructions with C expressions as operands.
47: (With them you can define ``built-in'' functions.)
48: * Asm Labels:: Specifying the assembler name to use for a C symbol.
49: * Explicit Reg Vars:: Defining variables residing in specified registers.
50: * Alternate Keywords:: @code{__const__}, @code{__asm__}, etc., for header files.
51: * Incomplete Enums:: @code{enum foo;}, with details to follow.
52: @end menu
53:
54: @node Statement Exprs
55: @section Statements and Declarations within Expressions
56: @cindex statements inside expressions
57: @cindex declarations inside expressions
58: @cindex expressions containing statements
59: @cindex macros, statements in expressions
60:
1.1.1.3 ! root 61: A compound statement enclosed in parentheses may appear as an expression
! 62: in GNU C. This allows you to use loops, switches, and local variables
! 63: within an expression.
! 64:
! 65: Recall that a compound statement is a sequence of statements surrounded
! 66: by braces; in this construct, parentheses go around the braces. For
1.1 root 67: example:
68:
69: @example
70: (@{ int y = foo (); int z;
71: if (y > 0) z = y;
72: else z = - y;
73: z; @})
74: @end example
75:
76: @noindent
77: is a valid (though slightly more complex than necessary) expression
78: for the absolute value of @code{foo ()}.
79:
1.1.1.3 ! root 80: The last thing in the compound statement should be an expression
! 81: followed by a semicolon; the value of this subexpression serves as the
! 82: value of the entire construct. (If you use some other kind of statement
! 83: last within the braces, the construct has type @code{void}, and thus
! 84: effectively no value.)
! 85:
1.1 root 86: This feature is especially useful in making macro definitions ``safe'' (so
87: that they evaluate each operand exactly once). For example, the
88: ``maximum'' function is commonly defined as a macro in standard C as
89: follows:
90:
91: @example
92: #define max(a,b) ((a) > (b) ? (a) : (b))
93: @end example
94:
95: @noindent
96: @cindex side effects, macro argument
97: But this definition computes either @var{a} or @var{b} twice, with bad
98: results if the operand has side effects. In GNU C, if you know the
99: type of the operands (here let's assume @code{int}), you can define
100: the macro safely as follows:
101:
102: @example
103: #define maxint(a,b) \
104: (@{int _a = (a), _b = (b); _a > _b ? _a : _b; @})
105: @end example
106:
107: Embedded statements are not allowed in constant expressions, such as
108: the value of an enumeration constant, the width of a bit field, or
109: the initial value of a static variable.
110:
111: If you don't know the type of the operand, you can still do this, but you
112: must use @code{typeof} (@pxref{Typeof}) or type naming (@pxref{Naming
113: Types}).
114:
115: @node Local Labels
116: @section Locally Declared Labels
117: @cindex local labels
118: @cindex macros, local labels
119:
120: Each statement expression is a scope in which @dfn{local labels} can be
121: declared. A local label is simply an identifier; you can jump to it
122: with an ordinary @code{goto} statement, but only from within the
123: statement expression it belongs to.
124:
125: A local label declaration looks like this:
126:
127: @example
128: __label__ @var{label};
129: @end example
130:
131: @noindent
132: or
133:
134: @example
135: __label__ @var{label1}, @var{label2}, @dots{};
136: @end example
137:
138: Local label declarations must come at the beginning of the statement
139: expression, right after the @samp{(@{}, before any ordinary
140: declarations.
141:
142: The label declaration defines the label @emph{name}, but does not define
143: the label itself. You must do this in the usual way, with
144: @code{@var{label}:}, within the statements of the statement expression.
145:
146: The local label feature is useful because statement expressions are
147: often used in macros. If the macro contains nested loops, a @code{goto}
148: can be useful for breaking out of them. However, an ordinary label
149: whose scope is the whole function cannot be used: if the macro can be
150: expanded several times in one function, the label will be multiply
151: defined in that function. A local label avoids this problem. For
152: example:
153:
154: @example
155: #define SEARCH(array, target) \
156: (@{ \
157: __label__ found; \
158: typeof (target) _SEARCH_target = (target); \
159: typeof (*(array)) *_SEARCH_array = (array); \
160: int i, j; \
161: int value; \
162: for (i = 0; i < max; i++) \
163: for (j = 0; j < max; j++) \
164: if (_SEARCH_array[i][j] == _SEARCH_target) \
165: @{ value = i; goto found; @} \
166: value = -1; \
167: found: \
168: value; \
169: @})
170: @end example
171:
172: @node Labels as Values
173: @section Labels as Values
174: @cindex labels as values
175: @cindex computed gotos
176: @cindex goto with computed label
177: @cindex address of a label
178:
179: You can get the address of a label defined in the current function
180: (or a containing function) with the unary operator @samp{&&}. The
181: value has type @code{void *}. This value is a constant and can be used
182: wherever a constant of that type is valid. For example:
183:
184: @example
185: void *ptr;
186: @dots{}
187: ptr = &&foo;
188: @end example
189:
190: To use these values, you need to be able to jump to one. This is done
191: with the computed goto statement@footnote{The analogous feature in
192: Fortran is called an assigned goto, but that name seems inappropriate in
193: C, where one can do more than simply store label addresses in label
194: variables.}, @code{goto *@var{exp};}. For example,
195:
196: @example
197: goto *ptr;
198: @end example
199:
200: @noindent
201: Any expression of type @code{void *} is allowed.
202:
203: One way of using these constants is in initializing a static array that
204: will serve as a jump table:
205:
206: @example
207: static void *array[] = @{ &&foo, &&bar, &&hack @};
208: @end example
209:
210: Then you can select a label with indexing, like this:
211:
212: @example
213: goto *array[i];
214: @end example
215:
216: @noindent
217: Note that this does not check whether the subscript is in bounds---array
218: indexing in C never does that.
219:
220: Such an array of label values serves a purpose much like that of the
221: @code{switch} statement. The @code{switch} statement is cleaner, so
222: use that rather than an array unless the problem does not fit a
223: @code{switch} statement very well.
224:
225: Another use of label values is in an interpreter for threaded code.
226: The labels within the interpreter function can be stored in the
227: threaded code for super-fast dispatching.
228:
1.1.1.3 ! root 229: You can use this mechanism to jump to code in a different function. If
! 230: you do that, totally unpredictable things will happen. The best way to
! 231: avoid this is to store the label address only in automatic variables and
! 232: never pass it as an argument.
! 233:
1.1 root 234: @node Nested Functions
235: @section Nested Functions
236: @cindex nested functions
237: @cindex downward funargs
238: @cindex thunks
239:
240: A @dfn{nested function} is a function defined inside another function.
241: The nested function's name is local to the block where it is defined.
242: For example, here we define a nested function named @code{square},
243: and call it twice:
244:
245: @example
246: foo (double a, double b)
247: @{
248: double square (double z) @{ return z * z; @}
249:
250: return square (a) + square (b);
251: @}
252: @end example
253:
254: The nested function can access all the variables of the containing
255: function that are visible at the point of its definition. This is
256: called @dfn{lexical scoping}. For example, here we show a nested
257: function which uses an inherited variable named @code{offset}:
258:
259: @example
260: bar (int *array, int offset, int size)
261: @{
262: int access (int *array, int index)
263: @{ return array[index + offset]; @}
264: int i;
265: @dots{}
266: for (i = 0; i < size; i++)
267: @dots{} access (array, i) @dots{}
268: @}
269: @end example
270:
271: It is possible to call the nested function from outside the scope of its
272: name by storing its address or passing the address to another function:
273:
274: @example
275: hack (int *array, int size)
276: @{
277: void store (int index, int value)
278: @{ array[index] = value; @}
279:
280: intermediate (store, size);
281: @}
282: @end example
283:
284: Here, the function @code{intermediate} receives the address of
285: @code{store} as an argument. If @code{intermediate} calls
286: @code{store}, the arguments given to @code{store} are used to store
287: into @code{array}. But this technique works only so long as the
288: containing function (@code{hack}, in this example) does not exit. If
289: you try to call the nested function through its address after the
290: containing function has exited, all hell will break loose.
291:
292: A nested function can jump to a label inherited from a containing
293: function, provided the label was explicitly declared in the containing
294: function (@pxref{Local Labels}). Such a jump returns instantly to the
295: containing function, exiting the nested function which did the
296: @code{goto} and any intermediate functions as well. Here is an example:
297:
298: @example
299: bar (int *array, int offset, int size)
300: @{
301: __label__ failure;
302: int access (int *array, int index)
303: @{
304: if (index > size)
305: goto failure;
306: return array[index + offset];
307: @}
308: int i;
309: @dots{}
310: for (i = 0; i < size; i++)
311: @dots{} access (array, i) @dots{}
312: @dots{}
313: return 0;
314:
315: /* @r{Control comes here from @code{access}
316: if it detects an error.} */
317: failure:
318: return -1;
319: @}
320: @end example
321:
322: A nested function always has internal linkage. Declaring one with
323: @code{extern} is erroneous. If you need to declare the nested function
324: before its definition, use @code{auto} (which is otherwise meaningless
325: for function declarations).
326:
327: @example
328: bar (int *array, int offset, int size)
329: @{
330: __label__ failure;
331: auto int access (int *, int);
332: @dots{}
333: int access (int *array, int index)
334: @{
335: if (index > size)
336: goto failure;
337: return array[index + offset];
338: @}
339: @dots{}
340: @}
341: @end example
342:
343: @node Naming Types
344: @section Naming an Expression's Type
345: @cindex naming types
346:
347: You can give a name to the type of an expression using a @code{typedef}
348: declaration with an initializer. Here is how to define @var{name} as a
349: type name for the type of @var{exp}:
350:
351: @example
352: typedef @var{name} = @var{exp};
353: @end example
354:
355: This is useful in conjunction with the statements-within-expressions
356: feature. Here is how the two together can be used to define a safe
357: ``maximum'' macro that operates on any arithmetic type:
358:
359: @example
360: #define max(a,b) \
361: (@{typedef _ta = (a), _tb = (b); \
362: _ta _a = (a); _tb _b = (b); \
363: _a > _b ? _a : _b; @})
364: @end example
365:
366: @cindex underscores in variables in macros
367: @cindex @samp{_} in variables in macros
368: @cindex local variables in macros
369: @cindex variables, local, in macros
370: @cindex macros, local variables in
371:
372: The reason for using names that start with underscores for the local
373: variables is to avoid conflicts with variable names that occur within the
374: expressions that are substituted for @code{a} and @code{b}. Eventually we
375: hope to design a new form of declaration syntax that allows you to declare
376: variables whose scopes start only after their initializers; this will be a
377: more reliable way to prevent such conflicts.
378:
379: @node Typeof
380: @section Referring to a Type with @code{typeof}
381: @findex typeof
382: @findex sizeof
383: @cindex macros, types of arguments
384:
385: Another way to refer to the type of an expression is with @code{typeof}.
386: The syntax of using of this keyword looks like @code{sizeof}, but the
387: construct acts semantically like a type name defined with @code{typedef}.
388:
389: There are two ways of writing the argument to @code{typeof}: with an
390: expression or with a type. Here is an example with an expression:
391:
392: @example
393: typeof (x[0](1))
394: @end example
395:
396: @noindent
397: This assumes that @code{x} is an array of functions; the type described
398: is that of the values of the functions.
399:
400: Here is an example with a typename as the argument:
401:
402: @example
403: typeof (int *)
404: @end example
405:
406: @noindent
407: Here the type described is that of pointers to @code{int}.
408:
409: If you are writing a header file that must work when included in ANSI C
410: programs, write @code{__typeof__} instead of @code{typeof}.
411: @xref{Alternate Keywords}.
412:
413: A @code{typeof}-construct can be used anywhere a typedef name could be
414: used. For example, you can use it in a declaration, in a cast, or inside
415: of @code{sizeof} or @code{typeof}.
416:
417: @itemize @bullet
418: @item
419: This declares @code{y} with the type of what @code{x} points to.
420:
421: @example
422: typeof (*x) y;
423: @end example
424:
425: @item
426: This declares @code{y} as an array of such values.
427:
428: @example
429: typeof (*x) y[4];
430: @end example
431:
432: @item
433: This declares @code{y} as an array of pointers to characters:
434:
435: @example
436: typeof (typeof (char *)[4]) y;
437: @end example
438:
439: @noindent
440: It is equivalent to the following traditional C declaration:
441:
442: @example
443: char *y[4];
444: @end example
445:
446: To see the meaning of the declaration using @code{typeof}, and why it
447: might be a useful way to write, let's rewrite it with these macros:
448:
449: @example
450: #define pointer(T) typeof(T *)
451: #define array(T, N) typeof(T [N])
452: @end example
453:
454: @noindent
455: Now the declaration can be rewritten this way:
456:
457: @example
458: array (pointer (char), 4) y;
459: @end example
460:
461: @noindent
462: Thus, @code{array (pointer (char), 4)} is the type of arrays of 4
463: pointers to @code{char}.
464: @end itemize
465:
466: @node Lvalues
467: @section Generalized Lvalues
468: @cindex compound expressions as lvalues
469: @cindex expressions, compound, as lvalues
470: @cindex conditional expressions as lvalues
471: @cindex expressions, conditional, as lvalues
472: @cindex casts as lvalues
473: @cindex generalized lvalues
474: @cindex lvalues, generalized
475: @cindex extensions, @code{?:}
476: @cindex @code{?:} extensions
477: Compound expressions, conditional expressions and casts are allowed as
478: lvalues provided their operands are lvalues. This means that you can take
479: their addresses or store values into them.
480:
481: For example, a compound expression can be assigned, provided the last
482: expression in the sequence is an lvalue. These two expressions are
483: equivalent:
484:
485: @example
486: (a, b) += 5
487: a, (b += 5)
488: @end example
489:
490: Similarly, the address of the compound expression can be taken. These two
491: expressions are equivalent:
492:
493: @example
494: &(a, b)
495: a, &b
496: @end example
497:
498: A conditional expression is a valid lvalue if its type is not void and the
499: true and false branches are both valid lvalues. For example, these two
500: expressions are equivalent:
501:
502: @example
503: (a ? b : c) = 5
504: (a ? b = 5 : (c = 5))
505: @end example
506:
507: A cast is a valid lvalue if its operand is an lvalue. A simple
508: assignment whose left-hand side is a cast works by converting the
509: right-hand side first to the specified type, then to the type of the
510: inner left-hand side expression. After this is stored, the value is
511: converted back to the specified type to become the value of the
512: assignment. Thus, if @code{a} has type @code{char *}, the following two
513: expressions are equivalent:
514:
515: @example
516: (int)a = 5
517: (int)(a = (char *)(int)5)
518: @end example
519:
520: An assignment-with-arithmetic operation such as @samp{+=} applied to a cast
521: performs the arithmetic using the type resulting from the cast, and then
522: continues as in the previous case. Therefore, these two expressions are
523: equivalent:
524:
525: @example
526: (int)a += 5
527: (int)(a = (char *)(int) ((int)a + 5))
528: @end example
529:
530: You cannot take the address of an lvalue cast, because the use of its
531: address would not work out coherently. Suppose that @code{&(int)f} were
532: permitted, where @code{f} has type @code{float}. Then the following
533: statement would try to store an integer bit-pattern where a floating
534: point number belongs:
535:
536: @example
537: *&(int)f = 1;
538: @end example
539:
540: This is quite different from what @code{(int)f = 1} would do---that
541: would convert 1 to floating point and store it. Rather than cause this
1.1.1.2 root 542: inconsistency, we think it is better to prohibit use of @samp{&} on a cast.
1.1 root 543:
544: If you really do want an @code{int *} pointer with the address of
545: @code{f}, you can simply write @code{(int *)&f}.
546:
547: @node Conditionals
548: @section Conditional Expressions with Omitted Operands
549: @cindex conditional expressions, extensions
550: @cindex omitted middle-operands
551: @cindex middle-operands, omitted
552: @cindex extensions, @code{?:}
553: @cindex @code{?:} extensions
554:
555: The middle operand in a conditional expression may be omitted. Then
556: if the first operand is nonzero, its value is the value of the conditional
557: expression.
558:
559: Therefore, the expression
560:
561: @example
562: x ? : y
563: @end example
564:
565: @noindent
566: has the value of @code{x} if that is nonzero; otherwise, the value of
567: @code{y}.
568:
569: This example is perfectly equivalent to
570:
571: @example
572: x ? x : y
573: @end example
574:
575: @cindex side effect in ?:
576: @cindex ?: side effect
577: @noindent
578: In this simple case, the ability to omit the middle operand is not
579: especially useful. When it becomes useful is when the first operand does,
580: or may (if it is a macro argument), contain a side effect. Then repeating
581: the operand in the middle would perform the side effect twice. Omitting
582: the middle operand uses the value already computed without the undesirable
583: effects of recomputing it.
584:
585: @node Long Long
586: @section Double-Word Integers
587: @cindex @code{long long} data types
588: @cindex double-word arithmetic
589: @cindex multiprecision arithmetic
590:
591: GNU C supports data types for integers that are twice as long as
592: @code{long int}. Simply write @code{long long int} for a signed
593: integer, or @code{unsigned long long int} for an unsigned integer.
594:
595: You can use these types in arithmetic like any other integer types.
596: Addition, subtraction, and bitwise boolean operations on these types
597: are open-coded on all types of machines. Multiplication is open-coded
598: if the machine supports fullword-to-doubleword a widening multiply
599: instruction. Division and shifts are open-coded only on machines that
600: provide special support. The operations that are not open-coded use
601: special library routines that come with GNU CC.
602:
603: There may be pitfalls when you use @code{long long} types for function
604: arguments, unless you declare function prototypes. If a function
605: expects type @code{int} for its argument, and you pass a value of type
606: @code{long long int}, confusion will result because the caller and the
607: subroutine will disagree about the number of bytes for the argument.
608: Likewise, if the function expects @code{long long int} and you pass
609: @code{int}. The best way to avoid such problems is to use prototypes.
610:
611: @node Zero Length
612: @section Arrays of Length Zero
613: @cindex arrays of length zero
614: @cindex zero-length arrays
615: @cindex length-zero arrays
616:
617: Zero-length arrays are allowed in GNU C. They are very useful as the last
618: element of a structure which is really a header for a variable-length
619: object:
620:
621: @example
622: struct line @{
623: int length;
624: char contents[0];
625: @};
626:
627: @{
628: struct line *thisline = (struct line *)
629: malloc (sizeof (struct line) + this_length);
630: thisline->length = this_length;
631: @}
632: @end example
633:
634: In standard C, you would have to give @code{contents} a length of 1, which
635: means either you waste space or complicate the argument to @code{malloc}.
636:
637: @node Variable Length
638: @section Arrays of Variable Length
639: @cindex variable-length arrays
640: @cindex arrays of variable length
641:
642: Variable-length automatic arrays are allowed in GNU C. These arrays are
643: declared like any other automatic arrays, but with a length that is not
644: a constant expression. The storage is allocated at the point of
645: declaration and deallocated when the brace-level is exited. For
646: example:
647:
648: @example
649: FILE *
650: concat_fopen (char *s1, char *s2, char *mode)
651: @{
652: char str[strlen (s1) + strlen (s2) + 1];
653: strcpy (str, s1);
654: strcat (str, s2);
655: return fopen (str, mode);
656: @}
657: @end example
658:
659: @cindex scope of a variable length array
660: @cindex variable-length array scope
661: @cindex deallocating variable length arrays
662: Jumping or breaking out of the scope of the array name deallocates the
663: storage. Jumping into the scope is not allowed; you get an error
664: message for it.
665:
666: @cindex @code{alloca} vs variable-length arrays
667: You can use the function @code{alloca} to get an effect much like
668: variable-length arrays. The function @code{alloca} is available in
669: many other C implementations (but not in all). On the other hand,
670: variable-length arrays are more elegant.
671:
672: There are other differences between these two methods. Space allocated
673: with @code{alloca} exists until the containing @emph{function} returns.
674: The space for a variable-length array is deallocated as soon as the array
675: name's scope ends. (If you use both variable-length arrays and
676: @code{alloca} in the same function, deallocation of a variable-length array
677: will also deallocate anything more recently allocated with @code{alloca}.)
678:
679: You can also use variable-length arrays as arguments to functions:
680:
681: @example
682: struct entry
683: tester (int len, char data[len][len])
684: @{
685: @dots{}
686: @}
687: @end example
688:
689: The length of an array is computed once when the storage is allocated
690: and is remembered for the scope of the array in case you access it with
691: @code{sizeof}.
692:
693: If you want to pass the array first and the length afterward, you can
694: use a forward declaration in the parameter list---another GNU extension.
695:
696: @example
697: struct entry
698: tester (int len; char data[len][len], int len)
699: @{
700: @dots{}
701: @}
702: @end example
703:
704: @cindex parameter forward declaration
705: The @samp{int len} before the semicolon is a @dfn{parameter forward
706: declaration}, and it serves the purpose of making the name @code{len}
707: known when the declaration of @code{data} is parsed.
708:
709: You can write any number of such parameter forward declarations in the
710: parameter list. They can be separated by commas or semicolons, but the
711: last one must end with a semicolon, which is followed by the ``real''
712: parameter declarations. Each forward declaration must match a ``real''
713: declaration in parameter name and data type.
714:
1.1.1.3 ! root 715: @node Macro Varargs
! 716: @section Macros with Variable Numbers of Arguments
! 717: @cindex variable number of arguments
! 718: @cindex macro with variable arguments
! 719: @cindex rest argument (in macro)
! 720:
! 721: In GNU C, a macro can accept a variable number of arguments, much as a
! 722: function can. The syntax for defining the macro looks much like that
! 723: used for a function. Here is an example:
! 724:
! 725: @example
! 726: #define eprintf(format, args...) \
! 727: fprintf (stderr, format, ## args)
! 728: @end example
! 729:
! 730: Here @code{args} is a @dfn{rest argument}: it takes in zero or more
! 731: arguments, as many as the call contains. All of them plus the commas
! 732: between them form the value of @code{args}, which is substituted into
! 733: the macro body where @code{args} is used. Thus, we have these
! 734: expansions:
! 735:
! 736: @example
! 737: eprintf ("%s:%d: ", input_file_name, line_number)
! 738: @expansion{}
! 739: fprintf (stderr, "%s:%d: ", input_file_name, line_number)
! 740: @end example
! 741:
! 742: @noindent
! 743: Note that the comma after the string constant comes from the definition
! 744: of @code{eprintf}, whereas the last comma comes from the value of
! 745: @code{args}.
! 746:
! 747: The reason for using @samp{##} is to handle the case when @code{args}
! 748: matches no arguments at all. In this case, @code{args} has an empty
! 749: value. In this case, the second comma in the definition becomes an
! 750: embarrassment: if it got through to the expansion of the macro, we would
! 751: get something like this:
! 752:
! 753: @example
! 754: fprintf (stderr, "success!\n", )
! 755: @end example
! 756:
! 757: @noindent
! 758: which is invalid C syntax. @samp{##} gets rid of the comma, so we get
! 759: the following instead:
! 760:
! 761: @example
! 762: fprintf (stderr, "success!\n")
! 763: @end example
! 764:
! 765: This is a special feature of the GNU C preprocessor: @samp{##} adjacent
! 766: to a rest argument discards the token on the other side of the
! 767: @samp{##}, if the rest argument value is empty.
! 768:
1.1 root 769: @node Subscripting
770: @section Non-Lvalue Arrays May Have Subscripts
771: @cindex subscripting
772: @cindex arrays, non-lvalue
773:
774: @cindex subscripting and function values
775: Subscripting is allowed on arrays that are not lvalues, even though the
776: unary @samp{&} operator is not. For example, this is valid in GNU C though
777: not valid in other C dialects:
778:
779: @example
780: struct foo @{int a[4];@};
781:
782: struct foo f();
783:
784: bar (int index)
785: @{
786: return f().a[index];
787: @}
788: @end example
789:
790: @node Pointer Arith
791: @section Arithmetic on @code{void}- and Function-Pointers
792: @cindex void pointers, arithmetic
793: @cindex void, size of pointer to
794: @cindex function pointers, arithmetic
795: @cindex function, size of pointer to
796:
797: In GNU C, addition and subtraction operations are supported on pointers to
798: @code{void} and on pointers to functions. This is done by treating the
799: size of a @code{void} or of a function as 1.
800:
801: A consequence of this is that @code{sizeof} is also allowed on @code{void}
802: and on function types, and returns 1.
803:
804: The option @samp{-Wpointer-arith} requests a warning if these extensions
805: are used.
806:
807: @node Initializers
808: @section Non-Constant Initializers
809: @cindex initializers, non-constant
810: @cindex non-constant initializers
811:
812: The elements of an aggregate initializer for an automatic variable are
813: not required to be constant expressions in GNU C. Here is an example of
814: an initializer with run-time varying elements:
815:
816: @example
817: foo (float f, float g)
818: @{
819: float beat_freqs[2] = @{ f-g, f+g @};
820: @dots{}
821: @}
822: @end example
823:
824: @node Constructors
825: @section Constructor Expressions
826: @cindex constructor expressions
827: @cindex initializations in expressions
828: @cindex structures, constructor expression
829: @cindex expressions, constructor
830:
831: GNU C supports constructor expressions. A constructor looks like
832: a cast containing an initializer. Its value is an object of the
833: type specified in the cast, containing the elements specified in
834: the initializer.
835:
836: Usually, the specified type is a structure. Assume that
837: @code{struct foo} and @code{structure} are declared as shown:
838:
839: @example
840: struct foo @{int a; char b[2];@} structure;
841: @end example
842:
843: @noindent
844: Here is an example of constructing a @code{struct foo} with a constructor:
845:
846: @example
847: structure = ((struct foo) @{x + y, 'a', 0@});
848: @end example
849:
850: @noindent
851: This is equivalent to writing the following:
852:
853: @example
854: @{
855: struct foo temp = @{x + y, 'a', 0@};
856: structure = temp;
857: @}
858: @end example
859:
860: You can also construct an array. If all the elements of the constructor
861: are (made up of) simple constant expressions, suitable for use in
862: initializers, then the constructor is an lvalue and can be coerced to a
863: pointer to its first element, as shown here:
864:
865: @example
866: char **foo = (char *[]) @{ "x", "y", "z" @};
867: @end example
868:
869: Array constructors whose elements are not simple constants are
870: not very useful, because the constructor is not an lvalue. There
871: are only two valid ways to use it: to subscript it, or initialize
872: an array variable with it. The former is probably slower than a
873: @code{switch} statement, while the latter does the same thing an
874: ordinary C initializer would do. Here is an example of
875: subscripting an array constructor:
876:
877: @example
878: output = ((int[]) @{ 2, x, 28 @}) [input];
879: @end example
880:
881: Constructor expressions for scalar types and union types are is
882: also allowed, but then the constructor expression is equivalent
883: to a cast.
884:
885: @node Labeled Elements
886: @section Labeled Elements in Initializers
887: @cindex initializers with labeled elements
888: @cindex labeled elements in initializers
889: @cindex case labels in initializers
890:
891: Standard C requires the elements of an initializer to appear in a fixed
892: order, the same as the order of the elements in the array or structure
893: being initialized.
894:
895: In GNU C you can give the elements in any order, specifying the array
896: indices or structure field names they apply to.
897:
898: To specify an array index, write @samp{[@var{index}]} before the
899: element value. For example,
900:
901: @example
902: int a[6] = @{ [4] 29, [2] 15 @};
903: @end example
904:
905: @noindent
906: is equivalent to
907:
908: @example
909: int a[6] = @{ 0, 0, 15, 0, 29, 0 @};
910: @end example
911:
912: @noindent
913: The index values must be constant expressions, even if the array being
914: initialized is automatic.
915:
916: In a structure initializer, specify the name of a field to initialize
917: with @samp{@var{fieldname}:} before the element value. For example,
918: given the following structure,
919:
920: @example
921: struct point @{ int x, y; @};
922: @end example
923:
924: @noindent
925: the following initialization
926:
927: @example
928: struct point p = @{ y: yvalue, x: xvalue @};
929: @end example
930:
931: @noindent
932: is equivalent to
933:
934: @example
935: struct point p = @{ xvalue, yvalue @};
936: @end example
937:
938: You can also use an element label when initializing a union, to
939: specify which element of the union should be used. For example,
940:
941: @example
942: union foo @{ int i; double d; @};
943:
944: union foo f = @{ d: 4 @};
945: @end example
946:
947: @noindent
948: will convert 4 to a @code{double} to store it in the union using
949: the second element. By contrast, casting 4 to type @code{union foo}
950: would store it into the union as the integer @code{i}, since it is
951: an integer. (@xref{Cast to Union}.)
952:
953: You can combine this technique of naming elements with ordinary C
954: initialization of successive elements. Each initializer element that
955: does not have a label applies to the next consecutive element of the
956: array or structure. For example,
957:
958: @example
959: int a[6] = @{ [1] v1, v2, [4] v4 @};
960: @end example
961:
962: @noindent
963: is equivalent to
964:
965: @example
966: int a[6] = @{ 0, v1, v2, 0, v4, 0 @};
967: @end example
968:
969: Labeling the elements of an array initializer is especially useful
970: when the indices are characters or belong to an @code{enum} type.
971: For example:
972:
973: @example
974: int whitespace[256]
975: = @{ [' '] 1, ['\t'] 1, ['\h'] 1,
976: ['\f'] 1, ['\n'] 1, ['\r'] 1 @};
977: @end example
978:
979: @node Case Ranges
980: @section Case Ranges
981: @cindex case ranges
982: @cindex ranges in case statements
983:
984: You can specify a range of consecutive values in a single @code{case} label,
985: like this:
986:
987: @example
988: case @var{low} ... @var{high}:
989: @end example
990:
991: @noindent
992: This has the same effect as the proper number of individual @code{case}
993: labels, one for each integer value from @var{low} to @var{high}, inclusive.
994:
995: This feature is especially useful for ranges of ASCII character codes:
996:
997: @example
998: case 'A' ... 'Z':
999: @end example
1000:
1001: @strong{Be careful:} Write spaces around the @code{...}, for otherwise
1002: it may be parsed wrong when you use it with integer values. For example,
1003: write this:
1004:
1005: @example
1006: case 1 ... 5:
1007: @end example
1008:
1009: @noindent
1010: rather than this:
1011:
1012: @example
1013: case 1...5:
1014: @end example
1015:
1016: @node Cast to Union
1017: @section Cast to a Union Type
1018: @cindex cast to a union
1019: @cindex union, casting to a
1020:
1021: A cast to union type is like any other cast, except that the type
1022: specified is a union type. You can specify the type either with
1023: @code{union @var{tag}} or with a typedef name.
1024:
1025: The types that may be cast to the union type are those of the members
1026: of the union. Thus, given the following union and variables:
1027:
1028: @example
1029: union foo @{ int i; double d; @};
1030: int x;
1031: double y;
1032: @end example
1033:
1034: @noindent
1035: both @code{x} and @code{y} can be cast to type @code{union} foo.
1036:
1037: Using the cast as the right-hand side of an assignment to a variable of
1038: union type is equivalent to storing in a member of the union:
1039:
1040: @example
1041: union foo u;
1042: @dots{}
1043: u = (union foo) x @equiv{} u.i = x
1044: u = (union foo) y @equiv{} u.d = y
1045: @end example
1046:
1047: You can also use the union cast as a function argument:
1048:
1049: @example
1050: void hack (union foo);
1051: @dots{}
1052: hack ((union foo) x);
1053: @end example
1054:
1055: @node Function Attributes
1056: @section Declaring Attributes of Functions
1057: @cindex function attributes
1058: @cindex declaring attributes of functions
1059: @cindex functions that never return
1060: @cindex functions that have no side effects
1061: @cindex @code{volatile} applied to function
1062: @cindex @code{const} applied to function
1063:
1064: In GNU C, you declare certain things about functions called in your program
1065: which help the compiler optimize function calls.
1066:
1067: A few standard library functions, such as @code{abort} and @code{exit},
1068: cannot return. GNU CC knows this automatically. Some programs define
1069: their own functions that never return. You can declare them
1070: @code{volatile} to tell the compiler this fact. For example,
1071:
1072: @example
1073: extern void volatile fatal ();
1074:
1075: void
1076: fatal (@dots{})
1077: @{
1078: @dots{} /* @r{Print error message.} */ @dots{}
1079: exit (1);
1080: @}
1081: @end example
1082:
1083: The @code{volatile} keyword tells the compiler to assume that
1084: @code{fatal} cannot return. This makes slightly better code, but more
1085: importantly it helps avoid spurious warnings of uninitialized variables.
1086:
1087: It does not make sense for a @code{volatile} function to have a return
1088: type other than @code{void}.
1089:
1090: Many functions do not examine any values except their arguments, and
1091: have no effects except the return value. Such a function can be subject
1092: to common subexpression elimination and loop optimization just as an
1093: arithmetic operator would be. These functions should be declared
1094: @code{const}. For example,
1095:
1096: @example
1097: extern int const square ();
1098: @end example
1099:
1100: @noindent
1101: says that the hypothetical function @code{square} is safe to call
1102: fewer times than the program says.
1103:
1104: @cindex pointer arguments
1105: Note that a function that has pointer arguments and examines the data
1106: pointed to must @emph{not} be declared @code{const}. Likewise, a
1107: function that calls a non-@code{const} function usually must not be
1108: @code{const}. It does not make sense for a @code{const} function to
1109: return @code{void}.
1110:
1111: We recommend placing the keyword @code{const} after the function's
1112: return type. It makes no difference in the example above, but when the
1113: return type is a pointer, it is the only way to make the function itself
1114: const. For example,
1115:
1116: @example
1117: const char *mincp (int);
1118: @end example
1119:
1120: @noindent
1121: says that @code{mincp} returns @code{const char *}---a pointer to a
1122: const object. To declare @code{mincp} const, you must write this:
1123:
1124: @example
1125: char * const mincp (int);
1126: @end example
1127:
1128: @cindex @code{#pragma}, reason for not using
1129: @cindex pragma, reason for not using
1130: Some people object to this feature, suggesting that ANSI C's
1131: @code{#pragma} should be used instead. There are two reasons for not
1132: doing this.
1133:
1134: @enumerate
1135: @item
1136: It is impossible to generate @code{#pragma} commands from a macro.
1137:
1138: @item
1139: The @code{#pragma} command is just as likely as these keywords to mean
1140: something else in another compiler.
1141: @end enumerate
1142:
1143: These two reasons apply to almost any application that might be proposed
1144: for @code{#pragma}. It is basically a mistake to use @code{#pragma} for
1145: @emph{anything}.
1146:
1.1.1.3 ! root 1147: @node Function Prototypes
! 1148: @section Prototypes and Old-Style Function Definitions
! 1149: @cindex function prototype declarations
! 1150: @cindex old-style function definitions
! 1151: @cindex promotion of formal parameters
! 1152:
! 1153: GNU C extends ANSI C to allow a function prototype to override a later
! 1154: old-style non-prototype definition. Consider the following example:
! 1155:
! 1156: @example
! 1157: /* @r{Use prototypes unless the compiler is old-fashioned.} */
! 1158: #if __STDC__
! 1159: #define P((x)) (x)
! 1160: #else
! 1161: #define P((x)) ()
! 1162: #endif
! 1163:
! 1164: /* @r{Prototype function declaration.} */
! 1165: int isroot P((uid_t));
! 1166:
! 1167: /* @r{Old-style function definition.} */
! 1168: int
! 1169: isroot (x) /* ??? lossage here ??? */
! 1170: uid_t x;
! 1171: @{
! 1172: return x == 0;
! 1173: @}
! 1174: @end example
! 1175:
! 1176: Suppose the type @code{uid_t} happens to be @code{short}. ANSI C does
! 1177: not allow this example, because subword arguments in old-style
! 1178: non-prototype definitions are promoted. Therefore in this example the
! 1179: function definition's argument is really an @code{int}, which does not
! 1180: match the prototype argument type of @code{short}.
! 1181:
! 1182: This restriction of ANSI C makes it hard to write code that is portable
! 1183: to traditional C compilers, because the programmer does not know
! 1184: whether the @code{uid_t} type is @code{short}, @code{int}, or
! 1185: @code{long}. Therefore, in cases like these GNU C allows a prototype
! 1186: to override a later old-style definition. More precisely, in GNU C, a
! 1187: function prototype argument type overrides the argument type specified
! 1188: by a later old-style definition if the former type is the same as the
! 1189: latter type before promotion. Thus in GNU C the above example is
! 1190: equivalent to the following:
! 1191:
! 1192: @example
! 1193: int isroot (uid_t);
! 1194:
! 1195: int
! 1196: isroot (uid_t x)
! 1197: @{
! 1198: return x == 0;
! 1199: @}
! 1200: @end example
! 1201:
1.1 root 1202: @node Dollar Signs
1203: @section Dollar Signs in Identifier Names
1204: @cindex $
1205: @cindex dollar signs in identifier names
1206: @cindex identifier names, dollar signs in
1207:
1208: In GNU C, you may use dollar signs in identifier names. This is because
1209: many traditional C implementations allow such identifiers.
1210:
1211: Dollar signs are allowed on certain machines if you specify
1212: @samp{-traditional}. On a few systems they are allowed by default, even
1213: if @samp{-traditional} is not used. But they are never allowed if you
1214: specify @samp{-ansi}.
1215:
1216: There are certain ANSI C programs (obscure, to be sure) that would
1217: compile incorrectly if dollar signs were permitted in identifiers. For
1218: example:
1219:
1220: @example
1221: #define foo(a) #a
1222: #define lose(b) foo (b)
1223: #define test$
1224: lose (test)
1225: @end example
1226:
1227: @node Character Escapes
1228: @section The Character @key{ESC} in Constants
1229:
1230: You can use the sequence @samp{\e} in a string or character constant to
1231: stand for the ASCII character @key{ESC}.
1232:
1233: @node Alignment
1234: @section Inquiring on Alignment of Types or Variables
1235: @cindex alignment
1236: @cindex type alignment
1237: @cindex variable alignment
1238:
1239: The keyword @code{__alignof__} allows you to inquire about how an object
1240: is aligned, or the minimum alignment usually required by a type. Its
1241: syntax is just like @code{sizeof}.
1242:
1243: For example, if the target machine requires a @code{double} value to be
1244: aligned on an 8-byte boundary, then @code{__alignof__ (double)} is 8.
1245: This is true on many RISC machines. On more traditional machine
1246: designs, @code{__alignof__ (double)} is 4 or even 2.
1247:
1248: Some machines never actually require alignment; they allow reference to any
1249: data type even at an odd addresses. For these machines, @code{__alignof__}
1250: reports the @emph{recommended} alignment of a type.
1251:
1252: When the operand of @code{__alignof__} is an lvalue rather than a type, the
1253: value is the largest alignment that the lvalue is known to have. It may
1254: have this alignment as a result of its data type, or because it is part of
1255: a structure and inherits alignment from that structure. For example, after
1256: this declaration:
1257:
1258: @example
1259: struct foo @{ int x; char y; @} foo1;
1260: @end example
1261:
1262: @noindent
1263: the value of @code{__alignof__ (foo1.y)} is probably 2 or 4, the same as
1264: @code{__alignof__ (int)}, even though the data type of @code{foo1.y}
1265: does not itself demand any alignment.@refill
1266:
1267: @node Variable Attributes
1268: @section Specifying Attributes of Variables
1269: @cindex attribute of variables
1270: @cindex variable attributes
1271:
1272: The keyword @code{__attribute__} allows you to specify special
1273: attributes of variables or structure fields. The only attributes
1274: currently defined are the @code{aligned} and @code{format} attributes.
1275:
1276: The @code{aligned} attribute specifies the alignment of the variable or
1277: structure field. For example, the declaration:
1278:
1279: @example
1280: int x __attribute__ ((aligned (16))) = 0;
1281: @end example
1282:
1283: @noindent
1284: causes the compiler to allocate the global variable @code{x} on a
1285: 16-byte boundary. On a 68000, this could be used in conjunction with
1286: an @code{asm} expression to access the @code{move16} instruction which
1287: requires 16-byte aligned operands.
1288:
1289: You can also specify the alignment of structure fields. For example, to
1290: create a double-word aligned @code{int} pair, you could write:
1291:
1292: @example
1293: struct foo @{ int x[2] __attribute__ ((aligned (8))); @};
1294: @end example
1295:
1296: @noindent
1297: This is an alternative to creating a union with a @code{double} member
1298: that forces the union to be double-word aligned.
1299:
1300: It is not possible to specify the alignment of functions; the alignment
1301: of functions is determined by the machine's requirements and cannot be
1.1.1.3 ! root 1302: changed. You cannot specify alignment for a typedef name because such a
! 1303: name is just an alias, not a distinct type.
1.1 root 1304:
1305: The @code{format} attribute specifies that a function takes @code{printf}
1306: or @code{scanf} style arguments which should be type-checked against a
1307: format string. For example, the declaration:
1308:
1309: @example
1310: extern int
1311: my_printf (void *my_object, const char *my_format, ...)
1312: __attribute__ ((format (printf, 2, 3)));
1313: @end example
1314:
1315: @noindent
1316: causes the compiler to check the arguments in calls to @code{my_printf}
1317: for consistency with the @code{printf} style format string argument
1318: @code{my_format}.
1319:
1320: The first parameter of the @code{format} attribute determines how the
1321: format string is interpreted, and should be either @code{printf} or
1322: @code{scanf}. The second parameter specifies the number of the
1323: format string argument (starting from 1). The third parameter
1324: specifies the number of the first argument which should be
1325: checked against the format string. For functions where the
1326: arguments are not available to be checked (such as @code{vprintf}),
1327: specify the third parameter as zero. In this case the compiler only checks
1328: the format string for consistency.
1329:
1330: In the example above, the format string (@code{my_format}) is the second
1331: argument to @code{my_print} and the arguments to check start with the third
1332: argument, so the correct parameters for the format attribute are 2 and 3.
1333:
1334: The @code{format} attribute allows you to identify your own functions
1335: which take format strings as arguments, so that GNU CC can check the
1336: calls to these functions for errors. The compiler always
1337: checks formats for the ANSI library functions
1338: @code{printf}, @code{fprintf}, @code{sprintf},
1339: @code{scanf}, @code{fscanf}, @code{sscanf},
1340: @code{vprintf}, @code{vfprintf} and @code{vsprintf}
1341: whenever such warnings are requested (using @samp{-Wformat}), so there is no
1342: need to modify the header file @file{stdio.h}.
1343:
1344: @node Inline
1345: @section An Inline Function is As Fast As a Macro
1346: @cindex inline functions
1347: @cindex integrating function code
1348: @cindex open coding
1349: @cindex macros, inline alternative
1350:
1351: By declaring a function @code{inline}, you can direct GNU CC to integrate
1352: that function's code into the code for its callers. This makes execution
1353: faster by eliminating the function-call overhead; in addition, if any of
1354: the actual argument values are constant, their known values may permit
1355: simplifications at compile time so that not all of the inline function's
1356: code needs to be included.
1357:
1358: To declare a function inline, use the @code{inline} keyword in its
1359: declaration, like this:
1360:
1361: @example
1362: inline int
1363: inc (int *a)
1364: @{
1365: (*a)++;
1366: @}
1367: @end example
1368:
1369: (If you are writing a header file to be included in ANSI C programs, write
1370: @code{__inline__} instead of @code{inline}. @xref{Alternate Keywords}.)
1371:
1372: You can also make all ``simple enough'' functions inline with the option
1373: @samp{-finline-functions}. Note that certain usages in a function
1374: definition can make it unsuitable for inline substitution.
1375:
1376: @cindex inline functions, omission of
1377: When a function is both inline and @code{static}, if all calls to the
1378: function are integrated into the caller, and the function's address is
1379: never used, then the function's own assembler code is never referenced.
1380: In this case, GNU CC does not actually output assembler code for the
1381: function, unless you specify the option @samp{-fkeep-inline-functions}.
1382: Some calls cannot be integrated for various reasons (in particular,
1383: calls that precede the function's definition cannot be integrated, and
1384: neither can recursive calls within the definition). If there is a
1385: nonintegrated call, then the function is compiled to assembler code as
1386: usual. The function must also be compiled as usual if the program
1387: refers to its address, because that can't be inlined.
1388:
1389: @cindex non-static inline function
1390: When an inline function is not @code{static}, then the compiler must assume
1391: that there may be calls from other source files; since a global symbol can
1392: be defined only once in any program, the function must not be defined in
1393: the other source files, so the calls therein cannot be integrated.
1394: Therefore, a non-@code{static} inline function is always compiled on its
1395: own in the usual fashion.
1396:
1397: If you specify both @code{inline} and @code{extern} in the function
1398: definition, then the definition is used only for inlining. In no case
1399: is the function compiled on its own, not even if you refer to its
1400: address explicitly. Such an address becomes an external reference, as
1401: if you had only declared the function, and had not defined it.
1402:
1403: This combination of @code{inline} and @code{extern} has almost the
1404: effect of a macro. The way to use it is to put a function definition in
1405: a header file with these keywords, and put another copy of the
1406: definition (lacking @code{inline} and @code{extern}) in a library file.
1407: The definition in the header file will cause most calls to the function
1408: to be inlined. If any uses of the function remain, they will refer to
1409: the single copy in the library.
1410:
1411: @node Extended Asm
1412: @section Assembler Instructions with C Expression Operands
1413: @cindex extended @code{asm}
1414: @cindex @code{asm} expressions
1415: @cindex assembler instructions
1416: @cindex registers
1417:
1418: In an assembler instruction using @code{asm}, you can now specify the
1419: operands of the instruction using C expressions. This means no more
1420: guessing which registers or memory locations will contain the data you want
1421: to use.
1422:
1423: You must specify an assembler instruction template much like what appears
1424: in a machine description, plus an operand constraint string for each
1425: operand.
1426:
1427: For example, here is how to use the 68881's @code{fsinx} instruction:
1428:
1429: @example
1430: asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
1431: @end example
1432:
1433: @noindent
1434: @ifset INTERNALS
1435: Here @code{angle} is the C expression for the input operand while
1436: @code{result} is that of the output operand. Each has @samp{"f"} as its
1437: operand constraint, saying that a floating point register is required. The
1438: @samp{=} in @samp{=f} indicates that the operand is an output; all output
1439: operands' constraints must use @samp{=}. The constraints use the same
1440: language used in the machine description (@pxref{Constraints}).
1441: @end ifset
1442: @ifclear INTERNALS
1443: Here @code{angle} is the C expression for the input operand while
1444: @code{result} is that of the output operand. Each has @samp{"f"} as its
1445: operand constraint, saying that a floating point register is required. The
1446: @samp{=} in @samp{=f} indicates that the operand is an output; all output
1447: operands' constraints must use @samp{=}. The constraints use the same
1448: language used in the machine description (@pxref{Constraints,,Operand
1449: Constraints, gcc.info, Using and Porting GCC}).
1450: @end ifclear
1451:
1452: Each operand is described by an operand-constraint string followed by the C
1453: expression in parentheses. A colon separates the assembler template from
1454: the first output operand, and another separates the last output operand
1455: from the first input, if any. Commas separate output operands and separate
1456: inputs. The total number of operands is limited to ten or to the maximum
1457: number of operands in any instruction pattern in the machine description,
1458: whichever is greater.
1459:
1460: If there are no output operands, and there are input operands, then there
1461: must be two consecutive colons surrounding the place where the output
1462: operands would go.
1463:
1464: Output operand expressions must be lvalues; the compiler can check this.
1465: The input operands need not be lvalues. The compiler cannot check whether
1466: the operands have data types that are reasonable for the instruction being
1467: executed. It does not parse the assembler instruction template and does
1468: not know what it means, or whether it is valid assembler input. The
1469: extended @code{asm} feature is most often used for machine instructions
1470: that the compiler itself does not know exist.
1471:
1472: The output operands must be write-only; GNU CC will assume that the values
1473: in these operands before the instruction are dead and need not be
1474: generated. Extended asm does not support input-output or read-write
1475: operands. For this reason, the constraint character @samp{+}, which
1476: indicates such an operand, may not be used.
1477:
1478: When the assembler instruction has a read-write operand, or an operand
1479: in which only some of the bits are to be changed, you must logically
1480: split its function into two separate operands, one input operand and one
1481: write-only output operand. The connection between them is expressed by
1482: constraints which say they need to be in the same location when the
1483: instruction executes. You can use the same C expression for both
1484: operands, or different expressions. For example, here we write the
1485: (fictitious) @samp{combine} instruction with @code{bar} as its read-only
1486: source operand and @code{foo} as its read-write destination:
1487:
1488: @example
1489: asm ("combine %2,%0" : "=r" (foo) : "0" (foo), "g" (bar));
1490: @end example
1491:
1492: @noindent
1493: The constraint @samp{"0"} for operand 1 says that it must occupy the same
1494: location as operand 0. A digit in constraint is allowed only in an input
1495: operand, and it must refer to an output operand.
1496:
1497: Only a digit in the constraint can guarantee that one operand will be in
1498: the same place as another. The mere fact that @code{foo} is the value of
1499: both operands is not enough to guarantee that they will be in the same
1500: place in the generated assembler code. The following would not work:
1501:
1502: @example
1503: asm ("combine %2,%0" : "=r" (foo) : "r" (foo), "g" (bar));
1504: @end example
1505:
1506: Various optimizations or reloading could cause operands 0 and 1 to be in
1507: different registers; GNU CC knows no reason not to do so. For example, the
1508: compiler might find a copy of the value of @code{foo} in one register and
1509: use it for operand 1, but generate the output operand 0 in a different
1510: register (copying it afterward to @code{foo}'s own address). Of course,
1511: since the register for operand 1 is not even mentioned in the assembler
1512: code, the result will not work, but GNU CC can't tell that.
1513:
1514: Some instructions clobber specific hard registers. To describe this, write
1515: a third colon after the input operands, followed by the names of the
1516: clobbered hard registers (given as strings). Here is a realistic example
1517: for the Vax:
1518:
1519: @example
1520: asm volatile ("movc3 %0,%1,%2"
1521: : /* no outputs */
1522: : "g" (from), "g" (to), "g" (count)
1523: : "r0", "r1", "r2", "r3", "r4", "r5");
1524: @end example
1525:
1526: If you refer to a particular hardware register from the assembler code,
1527: then you will probably have to list the register after the third colon
1528: to tell the compiler that the register's value is modified. In many
1529: assemblers, the register names begin with @samp{%}; to produce one
1530: @samp{%} in the assembler code, you must write @samp{%%} in the input.
1531:
1.1.1.3 ! root 1532: If your assembler instruction can alter the condition code register,
! 1533: add @samp{cc} to the list of clobbered registers. GNU CC on some
! 1534: machines represents the condition codes as a specific hardware
! 1535: register; @samp{cc} serves to name this register. On other machines,
! 1536: the condition code is handled differently, and specifying @samp{cc}
! 1537: has no effect. But it is valid no matter what the machine.
! 1538:
1.1 root 1539: You can put multiple assembler instructions together in a single @code{asm}
1540: template, separated either with newlines (written as @samp{\n}) or with
1541: semicolons if the assembler allows such semicolons. The GNU assembler
1542: allows semicolons and all Unix assemblers seem to do so. The input
1543: operands are guaranteed not to use any of the clobbered registers, and
1544: neither will the output operands' addresses, so you can read and write the
1545: clobbered registers as many times as you like. Here is an example of
1546: multiple instructions in a template; it assumes that the subroutine
1547: @code{_foo} accepts arguments in registers 9 and 10:
1548:
1549: @example
1550: asm ("movl %0,r9;movl %1,r10;call _foo"
1551: : /* no outputs */
1552: : "g" (from), "g" (to)
1553: : "r9", "r10");
1554: @end example
1555:
1556: @ifset INTERNALS
1557: Unless an output operand has the @samp{&} constraint modifier, GNU CC may
1558: allocate it in the same register as an unrelated input operand, on the
1559: assumption that the inputs are consumed before the outputs are produced.
1560: This assumption may be false if the assembler code actually consists of
1561: more than one instruction. In such a case, use @samp{&} for each output
1562: operand that may not overlap an input.
1563: @xref{Modifiers}.
1564: @end ifset
1565: @ifclear INTERNALS
1566: Unless an output operand has the @samp{&} constraint modifier, GNU CC may
1567: allocate it in the same register as an unrelated input operand, on the
1568: assumption that the inputs are consumed before the outputs are produced.
1569: This assumption may be false if the assembler code actually consists of
1570: more than one instruction. In such a case, use @samp{&} for each output
1571: operand that may not overlap an input.
1572: @xref{Modifiers,,Constraint Modifier Characters,gcc.info,Using and
1573: Porting GCC}.
1574: @end ifclear
1575:
1576: If you want to test the condition code produced by an assembler instruction,
1577: you must include a branch and a label in the @code{asm} construct, as follows:
1578:
1579: @example
1580: asm ("clr %0;frob %1;beq 0f;mov #1,%0;0:"
1581: : "g" (result)
1582: : "g" (input));
1583: @end example
1584:
1585: @noindent
1586: This assumes your assembler supports local labels, as the GNU assembler
1587: and most Unix assemblers do.
1588:
1589: @cindex macros containing @code{asm}
1590: Usually the most convenient way to use these @code{asm} instructions is to
1591: encapsulate them in macros that look like functions. For example,
1592:
1593: @example
1594: #define sin(x) \
1595: (@{ double __value, __arg = (x); \
1596: asm ("fsinx %1,%0": "=f" (__value): "f" (__arg)); \
1597: __value; @})
1598: @end example
1599:
1600: @noindent
1601: Here the variable @code{__arg} is used to make sure that the instruction
1602: operates on a proper @code{double} value, and to accept only those
1603: arguments @code{x} which can convert automatically to a @code{double}.
1604:
1605: Another way to make sure the instruction operates on the correct data type
1606: is to use a cast in the @code{asm}. This is different from using a
1607: variable @code{__arg} in that it converts more different types. For
1608: example, if the desired type were @code{int}, casting the argument to
1609: @code{int} would accept a pointer with no complaint, while assigning the
1610: argument to an @code{int} variable named @code{__arg} would warn about
1611: using a pointer unless the caller explicitly casts it.
1612:
1613: If an @code{asm} has output operands, GNU CC assumes for optimization
1614: purposes that the instruction has no side effects except to change the
1615: output operands. This does not mean that instructions with a side effect
1616: cannot be used, but you must be careful, because the compiler may eliminate
1617: them if the output operands aren't used, or move them out of loops, or
1618: replace two with one if they constitute a common subexpression. Also, if
1619: your instruction does have a side effect on a variable that otherwise
1620: appears not to change, the old value of the variable may be reused later if
1621: it happens to be found in a register.
1622:
1623: You can prevent an @code{asm} instruction from being deleted, moved
1624: significantly, or combined, by writing the keyword @code{volatile} after
1625: the @code{asm}. For example:
1626:
1627: @example
1628: #define set_priority(x) \
1629: asm volatile ("set_priority %0": /* no outputs */ : "g" (x))
1630: @end example
1631:
1632: @noindent
1633: An instruction without output operands will not be deleted or moved
1634: significantly, regardless, unless it is unreachable.
1635:
1636: Note that even a volatile @code{asm} instruction can be moved in ways
1637: that appear insignificant to the compiler, such as across jump
1638: instructions. You can't expect a sequence of volatile @code{asm}
1639: instructions to remain perfectly consecutive. If you want consecutive
1640: output, use a single @code{asm}.
1641:
1642: It is a natural idea to look for a way to give access to the condition
1643: code left by the assembler instruction. However, when we attempted to
1644: implement this, we found no way to make it work reliably. The problem
1645: is that output operands might need reloading, which would result in
1646: additional following ``store'' instructions. On most machines, these
1647: instructions would alter the condition code before there was time to
1648: test it. This problem doesn't arise for ordinary ``test'' and
1649: ``compare'' instructions because they don't have any output operands.
1650:
1651: If you are writing a header file that should be includable in ANSI C
1652: programs, write @code{__asm__} instead of @code{asm}. @xref{Alternate
1653: Keywords}.
1654:
1655: @node Asm Labels
1656: @section Controlling Names Used in Assembler Code
1657: @cindex assembler names for identifiers
1658: @cindex names used in assembler code
1659: @cindex identifiers, names in assembler code
1660:
1661: You can specify the name to be used in the assembler code for a C
1662: function or variable by writing the @code{asm} (or @code{__asm__})
1663: keyword after the declarator as follows:
1664:
1665: @example
1666: int foo asm ("myfoo") = 2;
1667: @end example
1668:
1669: @noindent
1670: This specifies that the name to be used for the variable @code{foo} in
1671: the assembler code should be @samp{myfoo} rather than the usual
1672: @samp{_foo}.
1673:
1674: On systems where an underscore is normally prepended to the name of a C
1675: function or variable, this feature allows you to define names for the
1676: linker that do not start with an underscore.
1677:
1678: You cannot use @code{asm} in this way in a function @emph{definition}; but
1679: you can get the same effect by writing a declaration for the function
1680: before its definition and putting @code{asm} there, like this:
1681:
1682: @example
1683: extern func () asm ("FUNC");
1684:
1685: func (x, y)
1686: int x, y;
1687: @dots{}
1688: @end example
1689:
1690: It is up to you to make sure that the assembler names you choose do not
1691: conflict with any other assembler symbols. Also, you must not use a
1692: register name; that would produce completely invalid assembler code. GNU
1693: CC does not as yet have the ability to store static variables in registers.
1694: Perhaps that will be added.
1695:
1696: @node Explicit Reg Vars
1697: @section Variables in Specified Registers
1698: @cindex explicit register variables
1699: @cindex variables in specified registers
1700: @cindex specified registers
1701: @cindex registers, global allocation
1702:
1703: GNU C allows you to put a few global variables into specified hardware
1704: registers. You can also specify the register in which an ordinary
1705: register variable should be allocated.
1706:
1707: @itemize @bullet
1708: @item
1709: Global register variables reserve registers throughout the program.
1710: This may be useful in programs such as programming language
1711: interpreters which have a couple of global variables that are accessed
1712: very often.
1713:
1714: @item
1715: Local register variables in specific registers do not reserve the
1716: registers. The compiler's data flow analysis is capable of determining
1717: where the specified registers contain live values, and where they are
1718: available for other uses.
1719:
1720: These local variables are sometimes convenient for use with the extended
1721: @code{asm} feature (@pxref{Extended Asm}), if you want to write one
1722: output of the assembler instruction directly into a particular register.
1723: (This will work provided the register you specify fits the constraints
1724: specified for that operand in the @code{asm}.)
1725: @end itemize
1726:
1727: @menu
1728: * Global Reg Vars::
1729: * Local Reg Vars::
1730: @end menu
1731:
1732: @node Global Reg Vars
1733: @subsection Defining Global Register Variables
1734: @cindex global register variables
1735: @cindex registers, global variables in
1736:
1737: You can define a global register variable in GNU C like this:
1738:
1739: @example
1740: register int *foo asm ("a5");
1741: @end example
1742:
1743: @noindent
1744: Here @code{a5} is the name of the register which should be used. Choose a
1745: register which is normally saved and restored by function calls on your
1746: machine, so that library routines will not clobber it.
1747:
1748: Naturally the register name is cpu-dependent, so you would need to
1749: conditionalize your program according to cpu type. The register
1750: @code{a5} would be a good choice on a 68000 for a variable of pointer
1751: type. On machines with register windows, be sure to choose a ``global''
1752: register that is not affected magically by the function call mechanism.
1753:
1754: In addition, operating systems on one type of cpu may differ in how they
1755: name the registers; then you would need additional conditionals. For
1756: example, some 68000 operating systems call this register @code{%a5}.
1757:
1758: Eventually there may be a way of asking the compiler to choose a register
1759: automatically, but first we need to figure out how it should choose and
1760: how to enable you to guide the choice. No solution is evident.
1761:
1762: Defining a global register variable in a certain register reserves that
1763: register entirely for this use, at least within the current compilation.
1764: The register will not be allocated for any other purpose in the functions
1765: in the current compilation. The register will not be saved and restored by
1766: these functions. Stores into this register are never deleted even if they
1767: would appear to be dead, but references may be deleted or moved or
1768: simplified.
1769:
1770: It is not safe to access the global register variables from signal
1771: handlers, or from more than one thread of control, because the system
1772: library routines may temporarily use the register for other things (unless
1773: you recompile them specially for the task at hand).
1774:
1775: @cindex @code{qsort}, and global register variables
1776: It is not safe for one function that uses a global register variable to
1777: call another such function @code{foo} by way of a third function
1778: @code{lose} that was compiled without knowledge of this variable (i.e. in a
1779: different source file in which the variable wasn't declared). This is
1780: because @code{lose} might save the register and put some other value there.
1781: For example, you can't expect a global register variable to be available in
1782: the comparison-function that you pass to @code{qsort}, since @code{qsort}
1783: might have put something else in that register. (If you are prepared to
1784: recompile @code{qsort} with the same global register variable, you can
1785: solve this problem.)
1786:
1787: If you want to recompile @code{qsort} or other source files which do not
1788: actually use your global register variable, so that they will not use that
1789: register for any other purpose, then it suffices to specify the compiler
1790: option @samp{-ffixed-@var{reg}}. You need not actually add a global
1791: register declaration to their source code.
1792:
1793: A function which can alter the value of a global register variable cannot
1794: safely be called from a function compiled without this variable, because it
1795: could clobber the value the caller expects to find there on return.
1796: Therefore, the function which is the entry point into the part of the
1797: program that uses the global register variable must explicitly save and
1798: restore the value which belongs to its caller.
1799:
1800: @cindex register variable after @code{longjmp}
1801: @cindex global register after @code{longjmp}
1802: @cindex value after @code{longjmp}
1803: @findex longjmp
1804: @findex setjmp
1805: On most machines, @code{longjmp} will restore to each global register
1806: variable the value it had at the time of the @code{setjmp}. On some
1807: machines, however, @code{longjmp} will not change the value of global
1808: register variables. To be portable, the function that called @code{setjmp}
1809: should make other arrangements to save the values of the global register
1810: variables, and to restore them in a @code{longjmp}. This way, the same
1811: thing will happen regardless of what @code{longjmp} does.
1812:
1813: All global register variable declarations must precede all function
1814: definitions. If such a declaration could appear after function
1815: definitions, the declaration would be too late to prevent the register from
1816: being used for other purposes in the preceding functions.
1817:
1818: Global register variables may not have initial values, because an
1819: executable file has no means to supply initial contents for a register.
1820:
1821: On the Sparc, there are reports that g3 @dots{} g7 are suitable
1822: registers, but certain library functions, such as @code{getwd}, as well
1823: as the subroutines for division and remainder, modify g3 and g4. g1 and
1824: g2 are local temporaries.
1825:
1826: On the 68000, a2 @dots{} a5 should be suitable, as should d2 @dots{} d7.
1827: Of course, it will not do to use more than a few of those.
1828:
1829: @node Local Reg Vars
1830: @subsection Specifying Registers for Local Variables
1831: @cindex local variables, specifying registers
1832: @cindex specifying registers for local variables
1833: @cindex registers for local variables
1834:
1835: You can define a local register variable with a specified register
1836: like this:
1837:
1838: @example
1839: register int *foo asm ("a5");
1840: @end example
1841:
1842: @noindent
1843: Here @code{a5} is the name of the register which should be used. Note
1844: that this is the same syntax used for defining global register
1845: variables, but for a local variable it would appear within a function.
1846:
1847: Naturally the register name is cpu-dependent, but this is not a
1848: problem, since specific registers are most often useful with explicit
1849: assembler instructions (@pxref{Extended Asm}). Both of these things
1850: generally require that you conditionalize your program according to
1851: cpu type.
1852:
1853: In addition, operating systems on one type of cpu may differ in how they
1854: name the registers; then you would need additional conditionals. For
1855: example, some 68000 operating systems call this register @code{%a5}.
1856:
1857: Eventually there may be a way of asking the compiler to choose a register
1858: automatically, but first we need to figure out how it should choose and
1859: how to enable you to guide the choice. No solution is evident.
1860:
1861: Defining such a register variable does not reserve the register; it
1862: remains available for other uses in places where flow control determines
1863: the variable's value is not live. However, these registers are made
1864: unavailable for use in the reload pass. I would not be surprised if
1865: excessive use of this feature leaves the compiler too few available
1866: registers to compile certain functions.
1867:
1868: @node Alternate Keywords
1869: @section Alternate Keywords
1870: @cindex alternate keywords
1871: @cindex keywords, alternate
1872:
1873: The option @samp{-traditional} disables certain keywords; @samp{-ansi}
1874: disables certain others. This causes trouble when you want to use GNU C
1875: extensions, or ANSI C features, in a general-purpose header file that
1876: should be usable by all programs, including ANSI C programs and traditional
1877: ones. The keywords @code{asm}, @code{typeof} and @code{inline} cannot be
1878: used since they won't work in a program compiled with @samp{-ansi}, while
1879: the keywords @code{const}, @code{volatile}, @code{signed}, @code{typeof}
1880: and @code{inline} won't work in a program compiled with
1881: @samp{-traditional}.@refill
1882:
1883: The way to solve these problems is to put @samp{__} at the beginning and
1884: end of each problematical keyword. For example, use @code{__asm__}
1885: instead of @code{asm}, @code{__const__} instead of @code{const}, and
1886: @code{__inline__} instead of @code{inline}.
1887:
1888: Other C compilers won't accept these alternative keywords; if you want to
1889: compile with another compiler, you can define the alternate keywords as
1890: macros to replace them with the customary keywords. It looks like this:
1891:
1892: @example
1893: #ifndef __GNUC__
1894: #define __asm__ asm
1895: #endif
1896: @end example
1897:
1898: @samp{-pedantic} causes warnings for many GNU C extensions. You can
1899: prevent such warnings within one expression by writing
1900: @code{__extension__} before the expression. @code{__extension__} has no
1901: effect aside from this.
1902:
1903: @node Incomplete Enums
1904: @section Incomplete @code{enum} Types
1905:
1906: You can define an @code{enum} tag without specifying its possible values.
1907: This results in an incomplete type, much like what you get if you write
1908: @code{struct foo} without describing the elements. A later declaration
1909: which does specify the possible values completes the type.
1910:
1911: You can't allocate variables or storage using the type while it is
1912: incomplete. However, you can work with pointers to that type.
1913:
1914: This extension may not be very useful, but it makes the handling of
1915: @code{enum} more consistent with the way @code{struct} and @code{union}
1916: are handled.
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.