?? lang.texi
字號:
@node Language Features, Library Summary, System Configuration, Top@appendix C Language Facilities in the LibrarySome of the facilities implemented by the C library really should bethought of as parts of the C language itself. These facilities ought tobe documented in the C Language Manual, not in the library manual; butsince we don't have the language manual yet, and documentation for thesefeatures has been written, we are publishing it here.@menu* Consistency Checking:: Using @code{assert} to abort if something ``impossible'' happens.* Variadic Functions:: Defining functions with varying numbers of args. * Null Pointer Constant:: The macro @code{NULL}.* Important Data Types:: Data types for object sizes.* Data Type Measurements:: Parameters of data type representations.@end menu@node Consistency Checking@section Explicitly Checking Internal Consistency@cindex consistency checking@cindex impossible events@cindex assertionsWhen you're writing a program, it's often a good idea to put in checksat strategic places for ``impossible'' errors or violations of basicassumptions. These checks are helpful in debugging problems due tomisunderstandings between different parts of the program.@pindex assert.hThe @code{assert} macro, defined in the header file @file{assert.h},provides a convenient way to abort the program while printing a messageabout where in the program the error was detected.@vindex NDEBUGOnce you think your program is debugged, you can disable the errorchecks performed by the @code{assert} macro by recompiling with themacro @code{NDEBUG} defined. This means you don't actually have tochange the program source code to disable these checks.But disabling these consistency checks is undesirable unless they makethe program significantly slower. All else being equal, more errorchecking is good no matter who is running the program. A wise userwould rather have a program crash, visibly, than have it return nonsensewithout indicating anything might be wrong.@comment assert.h@comment ANSI@deftypefn Macro void assert (int @var{expression})Verify the programmer's belief that @var{expression} should be nonzeroat this point in the program.If @code{NDEBUG} is not defined, @code{assert} tests the value of@var{expression}. If it is false (zero), @code{assert} aborts theprogram (@pxref{Aborting a Program}) after printing a message of theform:@smallexample@file{@var{file}}:@var{linenum}: Assertion `@var{expression}' failed.@end smallexample@noindenton the standard error stream @code{stderr} (@pxref{Standard Streams}).The filename and line number are taken from the C preprocessor macros@code{__FILE__} and @code{__LINE__} and specify where the call to@code{assert} was written.If the preprocessor macro @code{NDEBUG} is defined at the point where@file{assert.h} is included, the @code{assert} macro is defined to doabsolutely nothing.@strong{Warning:} Even the argument expression @var{expression} is notevaluated if @code{NDEBUG} is in effect. So never use @code{assert}with arguments that involve side effects. For example, @code{assert(++i > 0);} is a bad idea, because @code{i} will not be incremented if@code{NDEBUG} is defined.@end deftypefn@strong{Usage note:} The @code{assert} facility is designed fordetecting @emph{internal inconsistency}; it is not suitable forreporting invalid input or improper usage by @emph{the user} of theprogram.The information in the diagnostic messages printed by the @code{assert}macro is intended to help you, the programmer, track down the cause of abug, but is not really useful for telling a user of your program why hisor her input was invalid or why a command could not be carried out. Soyou can't use @code{assert} to print the error messages for theseeventualities.What's more, your program should not abort when given invalid input, as@code{assert} would do---it should exit with nonzero status (@pxref{ExitStatus}) after printing its error messages, or perhaps read anothercommand or move on to the next input file.@xref{Error Messages}, for information on printing error messages forproblems that @emph{do not} represent bugs in the program.@node Variadic Functions@section Variadic Functions@cindex variable number of arguments@cindex variadic functions@cindex optional argumentsANSI C defines a syntax for declaring a function to take a variablenumber or type of arguments. (Such functions are referred to as@dfn{varargs functions} or @dfn{variadic functions}.) However, thelanguage itself provides no mechanism for such functions to access theirnon-required arguments; instead, you use the variable arguments macrosdefined in @file{stdarg.h}.This section describes how to declare variadic functions, how to writethem, and how to call them properly.@strong{Compatibility Note:} Many older C dialects provide a similar,but incompatible, mechanism for defining functions with variable numbersof arguments, using @file{varargs.h}.@menu* Why Variadic:: Reasons for making functions take variable arguments. * How Variadic:: How to define and call variadic functions.* Variadic Example:: A complete example.@end menu@node Why Variadic@subsection Why Variadic Functions are UsedOrdinary C functions take a fixed number of arguments. When you definea function, you specify the data type for each argument. Every call tothe function should supply the expected number of arguments, with typesthat can be converted to the specified ones. Thus, if the function@samp{foo} is declared with @code{int foo (int, char *);} then you mustcall it with two arguments, a number (any kind will do) and a stringpointer.But some functions perform operations that can meaningfully accept anunlimited number of arguments.In some cases a function can handle any number of values by operating onall of them as a block. For example, consider a function that allocatesa one-dimensional array with @code{malloc} to hold a specified set ofvalues. This operation makes sense for any number of values, as long asthe length of the array corresponds to that number. Without facilitiesfor variable arguments, you would have to define a separate function foreach possible array size.The library function @code{printf} (@pxref{Formatted Output}) is anexample of another class of function where variable arguments areuseful. This function prints its arguments (which can vary in type aswell as number) under the control of a format template string.These are good reasons to define a @dfn{variadic} function which canhandle as many arguments as the caller chooses to pass.Some functions such as @code{open} take a fixed set of arguments, butoccasionally ignore the last few. Strict adherence to ANSI C requiresthese functions to be defined as variadic; in practice, however, the GNUC compiler and most other C compilers let you define such a function totake a fixed set of arguments---the most it can ever use---and then only@emph{declare} the function as variadic (or not declare its argumentsat all!).@node How Variadic@subsection How Variadic Functions are Defined and UsedDefining and using a variadic function involves three steps:@itemize @bullet@item@emph{Define} the function as variadic, using an ellipsis(@samp{@dots{}}) in the argument list, and using special macros toaccess the variable arguments. @xref{Receiving Arguments}.@item@emph{Declare} the function as variadic, using a prototype with anellipsis (@samp{@dots{}}), in all the files which call it.@xref{Variadic Prototypes}.@item@emph{Call} the function by writing the fixed arguments followed by theadditional variable arguments. @xref{Calling Variadics}.@end itemize@menu* Variadic Prototypes:: How to make a prototype for a function with variable arguments.* Receiving Arguments:: Steps you must follow to access the optional argument values.* How Many Arguments:: How to decide whether there are more arguments. * Calling Variadics:: Things you need to know about calling variable arguments functions.* Argument Macros:: Detailed specification of the macros for accessing variable arguments.* Old Varargs:: The pre-ANSI way of defining variadic functions.@end menu@node Variadic Prototypes@subsubsection Syntax for Variable Arguments@cindex function prototypes (variadic)@cindex prototypes for variadic functions@cindex variadic function prototypesA function that accepts a variable number of arguments must be declaredwith a prototype that says so. You write the fixed arguments as usual,and then tack on @samp{@dots{}} to indicate the possibility of additional arguments. The syntax of ANSI C requires at least one fixedargument before the @samp{@dots{}}. For example,@smallexampleint func (const char *a, int b, @dots{})@{ @dots{}@} @end smallexample@noindentoutlines a definition of a function @code{func} which returns an@code{int} and takes two required arguments, a @code{const char *} andan @code{int}. These are followed by any number of anonymousarguments.@strong{Portability note:} For some C compilers, the last requiredargument must not be declared @code{register} in the functiondefinition. Furthermore, this argument's type must be@dfn{self-promoting}: that is, the default promotions must not changeits type. This rules out array and function types, as well as@code{float}, @code{char} (whether signed or not) and @w{@code{short int}}(whether signed or not). This is actually an ANSI C requirement.@node Receiving Arguments@subsubsection Receiving the Argument Values@cindex variadic function argument access@cindex arguments (variadic functions)Ordinary fixed arguments have individual names, and you can use thesenames to access their values. But optional arguments have nonames---nothing but @samp{@dots{}}. How can you access them?@pindex stdarg.hThe only way to access them is sequentially, in the order they werewritten, and you must use special macros from @file{stdarg.h} in thefollowing three step process:@enumerate@itemYou initialize an argument pointer variable of type @code{va_list} using@code{va_start}. The argument pointer when initialized points to thefirst optional argument.@itemYou access the optional arguments by successive calls to @code{va_arg}.The first call to @code{va_arg} gives you the first optional argument,the next call gives you the second, and so on.You can stop at any time if you wish to ignore any remaining optionalarguments. It is perfectly all right for a function to access fewerarguments than were supplied in the call, but you will get garbagevalues if you try to access too many arguments.@itemYou indicate that you are finished with the argument pointer variable bycalling @code{va_end}.(In practice, with most C compilers, calling @code{va_end} does nothingand you do not really need to call it. This is always true in the GNU Ccompiler. But you might as well call @code{va_end} just in case yourprogram is someday compiled with a peculiar compiler.)@end enumerate@xref{Argument Macros}, for the full definitions of @code{va_start}, @code{va_arg} and @code{va_end}.Steps 1 and 3 must be performed in the function that accepts theoptional arguments. However, you can pass the @code{va_list} variableas an argument to another function and perform all or part of step 2there.You can perform the entire sequence of the three steps multiple timeswithin a single function invocation. If you want to ignore the optionalarguments, you can do these steps zero times.You can have more than one argument pointer variable if you like. Youcan initialize each variable with @code{va_start} when you wish, andthen you can fetch arguments with each argument pointer as you wish.Each argument pointer variable will sequence through the same set ofargument values, but at its own pace.@strong{Portability note:} With some compilers, once you pass anargument pointer value to a subroutine, you must not keep using the sameargument pointer value after that subroutine returns. For fullportability, you should just pass it to @code{va_end}. This is actuallyan ANSI C requirement, but most ANSI C compilers work happilyregardless.@node How Many Arguments@subsubsection How Many Arguments Were Supplied@cindex number of arguments passed@cindex how many arguments@cindex arguments, how manyThere is no general way for a function to determine the number and typeof the optional arguments it was called with. So whoever designs thefunction typically designs a convention for the caller to tell it howmany arguments it has, and what kind. It is up to you to define anappropriate calling convention for each variadic function, and write allcalls accordingly.One kind of calling convention is to pass the number of optionalarguments as one of the fixed arguments. This convention works providedall of the optional arguments are of the same type.A similar alternative is to have one of the required arguments be a bitmask, with a bit for each possible purpose for which an optionalargument might be supplied. You would test the bits in a predefinedsequence; if the bit is set, fetch the value of the next argument,otherwise use a default value.A required argument can be used as a pattern to specify both the numberand types of the optional arguments. The format string argument to@code{printf} is one example of this (@pxref{Formatted Output Functions}).Another possibility is to pass an ``end marker'' value as the lastoptional argument. For example, for a function that manipulates anarbitrary number of pointer arguments, a null pointer might indicate theend of the argument list. (This assumes that a null pointer isn'totherwise meaningful to the function.) The @code{execl} function worksin just this way; see @ref{Executing a File}.@node Calling Variadics@subsubsection Calling Variadic Functions@cindex variadic functions, calling@cindex calling variadic functions@cindex declaring variadic functionsYou don't have to write anything special when you call a variadic function.Just write the arguments (required arguments, followed by optional ones)inside parentheses, separated by commas, as usual. But you should prepareby declaring the function with a prototype, and you must know how theargument values are converted.In principle, functions that are @emph{defined} to be variadic must alsobe @emph{declared} to be variadic using a function prototype wheneveryou call them. (@xref{Variadic Prototypes}, for how.) This is becausesome C compilers use a different calling convention to pass the same setof argument values to a function depending on whether that functiontakes variable arguments or fixed arguments.In practice, the GNU C compiler always passes a given set of argumenttypes in the same way regardless of whether they are optional orrequired. So, as long as the argument types are self-promoting, you cansafely omit declaring them. Usually it is a good idea to declare theargument types for variadic functions, and indeed for all functions.But there are a few functions which it is extremely convenient not tohave to declare as variadic---for example, @code{open} and@code{printf}.@cindex default argument promotions@cindex argument promotionSince the prototype doesn't specify types for optional arguments, in acall to a variadic function the @dfn{default argument promotions} areperformed on the optional argument values. This means the objects oftype @code{char} or @w{@code{short int}} (whether signed or not) arepromoted to either @code{int} or @w{@code{unsigned int}}, asappropriate; and that objects of type @code{float} are promoted to type@code{double}. So, if the caller passes a @code{char} as an optionalargument, it is promoted to an @code{int}, and the function should getit with @code{va_arg (@var{ap}, int)}.Conversion of the required arguments is controlled by the functionprototype in the usual way: the argument expression is converted to thedeclared argument type as if it were being assigned to a variable ofthat type.@node Argument Macros@subsubsection Argument Access MacrosHere are descriptions of the macros used to retrieve variable arguments.These macros are defined in the header file @file{stdarg.h}.@pindex stdarg.h@comment stdarg.h@comment ANSI@deftp {Data Type} va_listThe type @code{va_list} is used for argument pointer variables.@end deftp@comment stdarg.h@comment ANSI@deftypefn {Macro} void va_start (va_list @var{ap}, @var{last-required})This macro initializes the argument pointer variable @var{ap} to pointto the first of the optional arguments of the current function;@var{last-required} must be the last required argument to the function.@xref{Old Varargs}, for an alternate definition of @code{va_start}found in the header file @file{varargs.h}.@end deftypefn@comment stdarg.h@comment ANSI@deftypefn {Macro} @var{type} va_arg (va_list @var{ap}, @var{type})
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -