Advertisement
j0h

GNU C Language Intro and refference

j0h
Sep 6th, 2022 (edited)
3,153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Latex 431.91 KB | None | 0 0
  1. \input texinfo
  2.  
  3. @c Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  4.  
  5. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  6. licensed to the FSF.)
  7.  
  8. @c move alignment later?
  9.  
  10. @setfilename ./c
  11. @settitle GNU C Language Manual
  12. @documentencoding UTF-8
  13.  
  14. @smallbook
  15. @synindex vr fn
  16.  
  17. @copying
  18. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  19.  
  20. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  21. licensed to the FSF.)
  22.  
  23. @quotation
  24. Permission is granted to copy, distribute and/or modify this document
  25. under the terms of the GNU Free Documentation License, Version 1.3 or
  26. any later version published by the Free Software Foundation; with the
  27. Invariant Sections being ``GNU General Public License,'' with the
  28. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  29. Texts as in (a) below.  A copy of the license is included in the
  30. section entitled ``GNU Free Documentation License.''
  31.  
  32. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  33. modify this GNU manual.  Buying copies from the FSF supports it in
  34. developing GNU and promoting software freedom.''
  35. @end quotation
  36. @end copying
  37.  
  38. @dircategory Programming
  39. @direntry
  40. * C: (c).       GNU C Language Intro and Reference Manual
  41. @end direntry
  42.  
  43. @documentencoding UTF-8
  44.  
  45. @titlepage
  46. @sp 6
  47. @center @titlefont{GNU C}
  48. @center @titlefont{Language Intro}
  49. @center @titlefont{and}
  50. @center @titlefont{Reference Manual}
  51. @sp 4
  52. @c @center @value{EDITION} Edition
  53. @sp 5
  54. @center Richard Stallman
  55. @center and
  56. @center Trevis Rothwell
  57. @center plus Nelson Beebe
  58. @center on floating point
  59. @page
  60. @vskip 0pt plus 1filll
  61.  
  62. @insertcopying
  63.  
  64. @sp 2
  65. WILL BE Published by the Free Software Foundation @*
  66. 51 Franklin Street, Fifth Floor @*
  67. Boston, MA 02110-1301 USA @*
  68. ISBN ?-??????-??-?
  69.  
  70. @ignore
  71. @sp 1
  72. Cover art by J. Random Artist
  73. @end ignore
  74.  
  75. @end titlepage
  76.  
  77. @summarycontents
  78. @contents
  79.  
  80.  
  81. @node Top
  82. @ifnottex
  83. @top GNU C Manual
  84. @end ifnottex
  85. @iftex
  86. @top Preface
  87. @end iftex
  88.  
  89. This manual explains the C language for use with the GNU Compiler
  90. Collection (GCC) on the GNU/Linux system and other systems.  We refer
  91. to this dialect as GNU C.  If you already know C, you can use this as
  92. a reference manual.
  93.  
  94. If you understand basic concepts of programming but know nothing about
  95. C, you can read this manual sequentially from the beginning to learn
  96. the C language.
  97.  
  98. If you are a beginner to programming, we recommend you first learn a
  99. language with automatic garbage collection and no explicit pointers,
  100. rather than starting with C@.  Good choices include Lisp, Scheme,
  101. Python and Java.  C's explicit pointers mean that programmers must be
  102. careful to avoid certain kinds of errors.
  103.  
  104. C is a venerable language; it was first used in 1973.  The GNU C
  105. Compiler, which was subsequently extended into the GNU Compiler
  106. Collection, was first released in 1987.  Other important languages
  107. were designed based on C: once you know C, it gives you a useful base
  108. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  109.  
  110. The special advantage of C is that it is fairly simple while allowing
  111. close access to the computer's hardware, which previously required
  112. writing in assembler language to describe the individual machine
  113. instructions.  Some have called C a ``high-level assembler language''
  114. because of its explicit pointers and lack of automatic management of
  115. storage.  As one wag put it, ``C combines the power of assembler
  116. language with the convenience of assembler language.''  However, C is
  117. far more portable, and much easier to read and write, than assembler
  118. language.
  119.  
  120. This manual focuses on the GNU C language supported by the GNU
  121. Compiler Collection, version ???.  When a construct may be absent or
  122. work differently in other C compilers, we say so.  When it is not part
  123. of ISO standard C, we say it is a ``GNU C extension,'' because it is
  124. useful to know that; however, other dialects and standards are not the
  125. focus of this manual.  We keep those notes short, unless it is vital
  126. to say more.  For the same reason, we hardly mention C@t{++} or other
  127. languages that the GNU Compiler Collection supports.
  128.  
  129. Some aspects of the meaning of C programs depend on the target
  130. platform: which computer, and which operating system, the compiled
  131. code will run on.  Where this is the case, we say so.
  132.  
  133. The C language provides no built-in facilities for performing such
  134. common operations as input/output, memory management, string
  135. manipulation, and the like.  Instead, these facilities are defined in
  136. a standard library, which is automatically available in every C
  137. program.  @xref{Top, The GNU C Library, , libc, The GNU C Library
  138. Reference Manual}.
  139.  
  140. This manual incorporates the former GNU C Preprocessor Manual, which
  141. was among the earliest GNU Manuals.  It also uses some text from the
  142. earlier GNU C Manual that was written by Trevis Rothwell and James
  143. Youngman.
  144.  
  145. GNU C has many obscure features, each one either for historical
  146. compatibility or meant for very special situations.  We have left them
  147. to a companion manual, the GNU C Obscurities Manual, which will be
  148. published digitally later.
  149.  
  150. @menu
  151. * The First Example::             Getting started with basic C code.
  152. * Complete Program::              A whole example program
  153.                                    that can be compiled and run.
  154. * Storage::                       Basic layout of storage; bytes.
  155. * Beyond Integers::               Exploring different numeric types.
  156. * Lexical Syntax::                The various lexical components of C programs.
  157. * Arithmetic::                    Numeric computations.
  158. * Assignment Expressions::        Storing values in variables.
  159. * Execution Control Expressions:: Expressions combining values in various ways.
  160. * Binary Operator Grammar::       An overview of operator precedence.
  161. * Order of Execution::            The order of program execution.
  162. * Primitive Types::               More details about primitive data types.
  163. * Constants::                     Explicit constant values:
  164.                                    details and examples.
  165. * Type Size::                     The memory space occupied by a type.
  166. * Pointers::                      Creating and manipulating memory pointers.
  167. * Structures::                    Compound data types built
  168.                                    by grouping other types.
  169. * Arrays::                        Creating and manipulating arrays.
  170. * Enumeration Types::             Sets of integers with named values.
  171. * Defining Typedef Names::        Using @code{typedef} to define type names.
  172. * Statements::                    Controling program flow.
  173. * Variables::                     Details about declaring, initializing,
  174.                                    and using variables.
  175. * Type Qualifiers::               Mark variables for certain intended uses.
  176. * Functions::                     Declaring, defining, and calling functions.
  177. * Compatible Types::              How to tell if two types are compatible
  178.                                    with each other.
  179. * Type Conversions::              Converting between types.
  180. * Scope::                         Different categories of identifier scope.
  181. * Preprocessing::                 Using the GNU C preprocessor.
  182. * Integers in Depth::             How integer numbers are represented.
  183. * Floating Point in Depth::       How floating-point numbers are represented.
  184. * Compilation::                   How to compile multi-file programs.
  185. * Directing Compilation::         Operations that affect compilation
  186.                                    but don't change the program.
  187.  
  188. Appendices
  189.  
  190. * Type Alignment::                Where in memory a type can validly start.
  191. * Aliasing::                      Accessing the same data in two types.
  192. * Digraphs::                      Two-character aliases for some characters.
  193. * Attributes::                    Specifying additional information
  194.                                    in a declaration.
  195. * Signals::                       Fatal errors triggered in various scenarios.
  196. * GNU Free Documentation License::      The license for this manual.
  197. * Symbol Index::                  Keyword and symbol index.
  198. * Concept Index::                 Detailed topical index.
  199.  
  200. @detailmenu
  201. --- The Detailed Node Listing ---
  202.  
  203. * Recursive Fibonacci::          Writing a simple function recursively.
  204. * Stack::                        Each function call uses space in the stack.
  205. * Iterative Fibonacci::          Writing the same function iteratively.
  206. * Complete Example::             Turn the simple function into a full program.
  207. * Complete Explanation::         Explanation of each part of the example.
  208. * Complete Line-by-Line::        Explaining each line of the example.
  209. * Compile Example::              Using GCC to compile the example.
  210. * Float Example::                A function that uses floating-point numbers.
  211. * Array Example::                A function that works with arrays.
  212. * Array Example Call::           How to call that function.
  213. * Array Example Variations::     Different ways to write the call example.
  214.  
  215. Lexical Syntax
  216.  
  217. * English::                      Write programs in English!
  218. * Characters::                   The characters allowed in C programs.
  219. * Whitespace::                   The particulars of whitespace characters.
  220. * Comments::                     How to include comments in C code.
  221. * Identifiers::                  How to form identifiers (names).
  222. * Operators/Punctuation::        Characters used as operators or punctuation.
  223. * Line Continuation::            Splitting one line into multiple lines.
  224. * Digraphs::                     Two-character substitutes for some characters.
  225.  
  226. Arithmetic
  227.  
  228. * Basic Arithmetic::             Addition, subtraction, multiplication,
  229.                                   and division.
  230. * Integer Arithmetic::           How C performs arithmetic with integer values.
  231. * Integer Overflow::             When an integer value exceeds the range
  232.                                   of its type.
  233. * Mixed Mode::                   Calculating with both integer values
  234.                                   and floating-point values.
  235. * Division and Remainder::       How integer division works.
  236. * Numeric Comparisons::          Comparing numeric values for
  237.                                   equality or order.
  238. * Shift Operations::             Shift integer bits left or right.
  239. * Bitwise Operations::           Bitwise conjunction, disjunction, negation.
  240.  
  241. Assignment Expressions
  242.  
  243. * Simple Assignment::            The basics of storing a value.
  244. * Lvalues::                      Expressions into which a value can be stored.
  245. * Modifying Assignment::         Shorthand for changing an lvalue's contents.
  246. * Increment/Decrement::          Shorthand for incrementing and decrementing
  247.                                   an lvalue's contents.
  248. * Postincrement/Postdecrement::  Accessing then incrementing or decrementing.
  249. * Assignment in Subexpressions:: How to avoid ambiguity.
  250. * Write Assignments Separately:: Write assignments as separate statements.
  251.  
  252. Execution Control Expressions
  253.  
  254. * Logical Operators::            Logical conjunction, disjunction, negation.
  255. * Logicals and Comparison::      Logical operators with comparison operators.
  256. * Logicals and Assignments::     Assignments with logical operators.
  257. * Conditional Expression::       An if/else construct inside expressions.
  258. * Comma Operator::               Build a sequence of subexpressions.
  259.  
  260. Order of Execution
  261.  
  262. * Reordering of Operands::       Operations in C are not necessarily computed
  263.                                   in the order they are written.
  264. * Associativity and Ordering::   Some associative operations are performed
  265.                                   in a particular order; others are not.    
  266. * Sequence Points::              Some guarantees about the order of operations.
  267. * Postincrement and Ordering::   Ambiguous excution order with postincrement.
  268. * Ordering of Operands::         Evaluation order of operands
  269.                                   and function arguments.
  270. * Optimization and Ordering::    Compiler optimizations can reorder operations
  271.                                   only if it has no impact on program results.
  272.  
  273. Primitive Data Types
  274.  
  275. * Integer Types::                Description of integer types.
  276. * Floating-Point Data Types::    Description of floating-point types.
  277. * Complex Data Types::           Description of complex number types.
  278. * The Void Type::                A type indicating no value at all.
  279. * Other Data Types::             A brief summary of other types.
  280.  
  281. Constants
  282.  
  283. * Integer Constants::            Literal integer values.                  
  284. * Integer Const Type::           Types of literal integer values.
  285. * Floating Constants::           Literal floating-point values.
  286. * Imaginary Constants::          Literal imaginary number values.
  287. * Invalid Numbers::              Avoiding preprocessing number misconceptions.
  288. * Character Constants::          Literal character values.
  289. * Unicode Character Codes::      Unicode characters represented
  290.                                   in either UTF-16 or UTF-32.
  291. * Wide Character Constants::     Literal characters values larger than 8 bits.
  292. * String Constants::             Literal string values.
  293. * UTF-8 String Constants::       Literal UTF-8 string values.
  294. * Wide String Constants::        Literal string values made up of
  295.                                   16- or 32-bit characters.
  296.  
  297. Pointers
  298.  
  299. * Address of Data::              Using the ``address-of'' operator.
  300. * Pointer Types::                For each type, there is a pointer type.
  301. * Pointer Declarations::         Declaring variables with pointer types.
  302. * Pointer Type Designators::     Designators for pointer types.
  303. * Pointer Dereference::          Accessing what a pointer points at.
  304. * Null Pointers::                Pointers which do not point to any object.
  305. * Invalid Dereference::          Dereferencing null or invalid pointers.
  306. * Void Pointers::                Totally generic pointers, can cast to any.
  307. * Pointer Comparison::           Comparing memory address values.
  308. * Pointer Arithmetic::           Computing memory address values.
  309. * Pointers and Arrays::          Using pointer syntax instead of array syntax.
  310. * Pointer Arithmetic Low Level:: More about computing memory address values.
  311. * Pointer Increment/Decrement::  Incrementing and decrementing pointers.
  312. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  313. * Pointer-Integer Conversion::   Converting pointer types to integer types.
  314. * Printing Pointers::            Using @code{printf} for a pointer's value.
  315.  
  316. Structures
  317.  
  318. * Referencing Fields::           Accessing field values in a structure object.
  319. * Dynamic Memory Allocation::    Allocating space for objects
  320.                                   while the program is running.
  321. * Field Offset::                 Memory layout of fields within a structure.
  322. * Structure Layout::             Planning the memory layout of fields.
  323. * Packed Structures::            Packing structure fields as close as possible.
  324. * Bit Fields::                   Dividing integer fields
  325.                                   into fields with fewer bits.
  326. * Bit Field Packing::            How bit fields pack together in integers.
  327. * const Fields::                 Making structure fields immutable.
  328. * Zero Length::                  Zero-length array as a variable-length object.
  329. * Flexible Array Fields::        Another approach to variable-length objects.
  330. * Overlaying Structures::        Casting one structure type
  331.                                   over an object of another structure type.
  332. * Structure Assignment::         Assigning values to structure objects.
  333. * Unions::                       Viewing the same object in different types.
  334. * Packing With Unions::          Using a union type to pack various types into
  335.                                   the same memory space.
  336. * Cast to Union::                Casting a value one of the union's alternative
  337.                                   types to the type of the union itself.
  338. * Structure Constructors::       Building new structure objects.
  339. * Unnamed Types as Fields::      Fields' types do not always need names.
  340. * Incomplete Types::             Types which have not been fully defined.
  341. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  342. * Type Tags::                    Scope of structure and union type tags.
  343.  
  344. Arrays
  345.  
  346. * Accessing Array Elements::     How to access individual elements of an array.
  347. * Declaring an Array::           How to name and reserve space for a new array.
  348. * Strings::                      A string in C is a special case of array.
  349. * Incomplete Array Types::       Naming, but not allocating, a new array.
  350. * Limitations of C Arrays::      Arrays are not first-class objects.
  351. * Multidimensional Arrays::      Arrays of arrays.
  352. * Constructing Array Values::    Assigning values to an entire array at once.
  353. * Arrays of Variable Length::    Declaring arrays of non-constant size.
  354.  
  355. Statements
  356.  
  357. * Expression Statement::         Evaluate an expression, as a statement,
  358.                                   usually done for a side effect.
  359. * if Statement::                 Basic conditional execution.
  360. * if-else Statement::            Multiple branches for conditional execution.
  361. * Blocks::                       Grouping multiple statements together.
  362. * return Statement::             Return a value from a function.
  363. * Loop Statements::              Repeatedly executing a statement or block.
  364. * switch Statement::             Multi-way conditional choices.
  365. * switch Example::               A plausible example of using @code{switch}.
  366. * Duffs Device::                 A special way to use @code{switch}.
  367. * Case Ranges::                  Ranges of values for @code{switch} cases.
  368. * Null Statement::               A statement that does nothing.
  369. * goto Statement::               Jump to another point in the source code,
  370.                                   identified by a label.
  371. * Local Labels::                 Labels with limited scope.
  372. * Labels as Values::             Getting the address of a label.
  373. * Statement Exprs::              A series of statements used as an expression.
  374.  
  375. Variables
  376.  
  377. * Variable Declarations::        Name a variable and and reserve space for it.
  378. * Initializers::                 Assigning inital values to variables.
  379. * Designated Inits::             Assigning initial values to array elements
  380.                                   at particular array indices.
  381. * Auto Type::                    Obtaining the type of a variable.
  382. * Local Variables::              Variables declared in function definitions.
  383. * File-Scope Variables::         Variables declared outside of
  384.                                   function definitions.
  385. * Static Local Variables::       Variables declared within functions,
  386.                                   but with permanent storage allocation.
  387. * Extern Declarations::          Declaring a variable
  388.                                   which is allocated somewhere else.
  389. * Allocating File-Scope::        When is space allocated
  390.                                   for file-scope variables?
  391. * auto and register::            Historically used storage directions.
  392. * Omitting Types::               The bad practice of declaring variables
  393.                                   with implicit type.
  394.  
  395. Type Qualifiers
  396.  
  397. * const::                        Variables whose values don't change.
  398. * volatile::                     Variables whose values may be accessed
  399.                                   or changed outside of the control of
  400.                                   this program.
  401. * restrict Pointers::            Restricted pointers for code optimization.
  402. * restrict Pointer Example::     Example of how that works.
  403.  
  404. Functions
  405.  
  406. * Function Definitions::         Writing the body of a function.
  407. * Function Declarations::        Declaring the interface of a function.
  408. * Function Calls::               Using functions.
  409. * Function Call Semantics::      Call-by-value argument passing.
  410. * Function Pointers::            Using references to functions.
  411. * The main Function::            Where execution of a GNU C program begins.
  412.  
  413. Type Conversions
  414.  
  415. * Explicit Type Conversion::     Casting a value from one type to another.
  416. * Assignment Type Conversions::  Automatic conversion by assignment operation.
  417. * Argument Promotions::          Automatic conversion of function parameters.
  418. * Operand Promotions::           Automatic conversion of arithmetic operands.
  419. * Common Type::                  When operand types differ, which one is used?
  420.  
  421. Scope
  422.  
  423. * Scope::                        Different categories of identifier scope.
  424.  
  425. Preprocessing
  426.  
  427. * Preproc Overview::             Introduction to the C preprocessor.
  428. * Directives::                   The form of preprocessor directives.
  429. * Preprocessing Tokens::         The lexical elements of preprocessing.
  430. * Header Files::                 Including one source file in another.
  431. * Macros::                       Macro expansion by the preprocessor.
  432. * Conditionals::                 Controling whether to compile some lines
  433.                                   or ignore them.
  434. * Diagnostics::                  Reporting warnings and errors.
  435. * Line Control::                 Reporting source line numbers.
  436. * Null Directive::               A preprocessing no-op.
  437.  
  438. Integers in Depth
  439.  
  440. * Integer Representations::      How integer values appear in memory.
  441. * Maximum and Minimum Values::   Value ranges of integer types.
  442.  
  443. Floating Point in Depth
  444.  
  445. * Floating Representations::     How floating-point values appear in memory.
  446. * Floating Type Specs::          Precise details of memory representations.
  447. * Special Float Values::         Infinity, Not a Number, and Subnormal Numbers.
  448. * Invalid Optimizations::        Don't mess up non-numbers and signed zeros.
  449. * Exception Flags::              Handling certain conditions in floating point.
  450. * Exact Floating-Point::         Not all floating calculations lose precision.
  451. * Rounding::                     When a floating result can't be represented
  452.                                   exactly in the floating-point type in use.
  453. * Rounding Issues::              Avoid magnifying rounding errors.
  454. * Significance Loss::            Subtracting numbers that are almost equal.
  455. * Fused Multiply-Add::           Taking advantage of a special floating-point
  456.                                   instruction for faster execution.
  457. * Error Recovery::               Determining rounding errors.
  458. * Exact Floating Constants::     Precisely specified floating-point numbers.
  459. * Handling Infinity::            When floating calculation is out of range.
  460. * Handling NaN::                 What floating calculation is undefined.
  461. * Signed Zeros::                 Positive zero vs. negative zero.
  462. * Scaling by the Base::          A useful exact floating-point operation.
  463. * Rounding Control::             Specifying some rounding behaviors.
  464. * Machine Epsilon::              The smallest number you can add to 1.0
  465.                                   and get a sum which is larger than 1.0.
  466. * Complex Arithmetic::           Details of arithmetic with complex numbers.
  467. * Round-Trip Base Conversion::   What happens between base-2 and base-10.
  468. * Further Reading::              References for floating-point numbers.
  469.  
  470. Directing Compilation
  471.  
  472. * Pragmas::                      Controling compilation of some constructs.
  473. * Static Assertions::            Compile-time tests for conditions.    
  474.  
  475. @end detailmenu
  476. @end menu
  477.  
  478. @node The First Example
  479. @chapter The First Example
  480.  
  481. This chapter presents the source code for a very simple C program and
  482. uses it to explain a few features of the language.  If you already
  483. know the basic points of C presented in this chapter, you can skim it
  484. or skip it.
  485.  
  486. @menu
  487. * Recursive Fibonacci:: Writing a simple function recursively.
  488. * Stack::               Each function call uses space in the stack.
  489. * Iterative Fibonacci:: Writing the same function iteratively.
  490. @end menu
  491.  
  492. @node Recursive Fibonacci
  493. @section Example: Recursive Fibonacci
  494. @cindex recursive Fibonacci function
  495. @cindex Fibonacci function, recursive
  496.  
  497. To introduce the most basic features of C, let's look at code for a
  498. simple mathematical function that does calculations on integers.  This
  499. function calculates the @var{n}th number in the Fibonacci series, in
  500. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  501. 13, 21, 34, 55, @dots{}.
  502.  
  503. @example
  504. int
  505. fib (int n)
  506. @{
  507.  if (n <= 2)  /* @r{This avoids infinite recursion.}  */
  508.    return 1;
  509.  else
  510.    return fib (n - 1) + fib (n - 2);
  511. @}
  512. @end example
  513.  
  514. This very simple program illustrates several features of C:
  515.  
  516. @itemize @bullet
  517. @item
  518. A function definition, whose first two lines constitute the function
  519. header.  @xref{Function Definitions}.
  520.  
  521. @item
  522. A function parameter @code{n}, referred to as the variable @code{n}
  523. inside the function body.  @xref{Function Parameter Variables}.
  524. A function definition uses parameters to refer to the argument
  525. values provided in a call to that function.
  526.  
  527. @item
  528. Arithmetic.  C programs add with @samp{+} and subtract with
  529. @samp{-}.  @xref{Arithmetic}.
  530.  
  531. @item
  532. Numeric comparisons.  The operator @samp{<=} tests for ``less than or
  533. equal.''  @xref{Numeric Comparisons}.
  534.  
  535. @item
  536. Integer constants written in base 10.
  537. @xref{Integer Constants}.
  538.  
  539. @item
  540. A function call.  The function call @code{fib (n - 1)} calls the
  541. function @code{fib}, passing as its argument the value @code{n - 1}.
  542. @xref{Function Calls}.
  543.  
  544. @item
  545. A comment, which starts with @samp{/*} and ends with @samp{*/}.  The
  546. comment has no effect on the execution of the program.  Its purpose is
  547. to provide explanations to people reading the source code.  Including
  548. comments in the code is tremendously important---they provide
  549. background information so others can understand the code more quickly.
  550. @xref{Comments}.
  551.  
  552. @item
  553. Two kinds of statements, the @code{return} statement and the
  554. @code{if}@dots{}@code{else} statement.  @xref{Statements}.
  555.  
  556. @item
  557. Recursion.  The function @code{fib} calls itself; that is called a
  558. @dfn{recursive call}.  These are valid in C, and quite common.
  559.  
  560. The @code{fib} function would not be useful if it didn't return.
  561. Thus, recursive definitions, to be of any use, must avoid infinite
  562. recursion.
  563.  
  564. This function definition prevents infinite recursion by specially
  565. handling the case where @code{n} is two or less.  Thus the maximum
  566. depth of recursive calls is less than @code{n}.
  567. @end itemize
  568.  
  569. @menu
  570. * Function Header:: The function's name and how it is called.
  571. * Function Body::   Declarations and statements that implement the function.
  572. @end menu
  573.  
  574. @node Function Header
  575. @subsection Function Header
  576. @cindex function header
  577.  
  578. In our example, the first two lines of the function definition are the
  579. @dfn{header}.  Its purpose is to state the function's name and say how
  580. it is called:
  581.  
  582. @example
  583. int
  584. fib (int n)
  585. @end example
  586.  
  587. @noindent
  588. says that the function returns an integer (type @code{int}), its name is
  589. @code{fib}, and it takes one argument named @code{n} which is also an
  590. integer.  (Data types will be explained later, in @ref{Primitive Types}.)
  591.  
  592. @node Function Body
  593. @subsection Function Body
  594. @cindex function body
  595. @cindex recursion
  596.  
  597. The rest of the function definition is called the @dfn{function body}.
  598. Like every function body, this one starts with @samp{@{}, ends with
  599. @samp{@}}, and contains zero or more @dfn{statements} and
  600. @dfn{declarations}.  Statements specify actions to take, whereas
  601. declarations define names of variables, functions, and so on.  Each
  602. statement and each declaration ends with a semicolon (@samp{;}).
  603.  
  604. Statements and declarations often contain @dfn{expressions}; an
  605. expression is a construct whose execution produces a @dfn{value} of
  606. some data type, but may also take actions through ``side effects''
  607. that alter subsequent execution.  A statement, by contrast, does not
  608. have a value; it affects further execution of the program only through
  609. the actions it takes.
  610.  
  611. This function body contains no declarations, and just one statement,
  612. but that one is a complex statement in that it contains nested
  613. statements.  This function uses two kinds of statements:
  614.  
  615. @table @code
  616. @item return
  617. The @code{return} statement makes the function return immediately.
  618. It looks like this:
  619.  
  620. @example
  621. return @var{value};
  622. @end example
  623.  
  624. Its meaning is to compute the expression @var{value} and exit the
  625. function, making it return whatever value that expression produced.
  626. For instance,
  627.  
  628. @example
  629. return 1;
  630. @end example
  631.  
  632. @noindent
  633. returns the integer 1 from the function, and
  634.  
  635. @example
  636. return fib (n - 1) + fib (n - 2);
  637. @end example
  638.  
  639. @noindent
  640. returns a value computed by performing two function calls
  641. as specified and adding their results.
  642.  
  643. @item @code{if}@dots{}@code{else}
  644. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  645. Each time it executes, it chooses one of its two substatements to execute
  646. and ignores the other.  It looks like this:
  647.  
  648. @example
  649. if (@var{condition})
  650.  @var{if-true-statement}
  651. else
  652.  @var{if-false-statement}
  653. @end example
  654.  
  655. Its meaning is to compute the expression @var{condition} and, if it's
  656. ``true,'' execute @var{if-true-statement}.  Otherwise, execute
  657. @var{if-false-statement}.  @xref{if-else Statement}.
  658.  
  659. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  660. simply an expression.  It's considered ``true'' if its value is
  661. nonzero.  (A comparison operation, such as @code{n <= 2}, produces the
  662. value 1 if it's ``true'' and 0 if it's ``false.''  @xref{Numeric
  663. Comparisons}.)  Thus,
  664.  
  665. @example
  666. if (n <= 2)
  667.  return 1;
  668. else
  669.  return fib (n - 1) + fib (n - 2);
  670. @end example
  671.  
  672. @noindent
  673. first tests whether the value of @code{n} is less than or equal to 2.
  674. If so, the expression @code{n <= 2} has the value 1.  So execution
  675. continues with the statement
  676.  
  677. @example
  678. return 1;
  679. @end example
  680.  
  681. @noindent
  682. Otherwise, execution continues with this statement:
  683.  
  684. @example
  685. return fib (n - 1) + fib (n - 2);
  686. @end example
  687.  
  688. Each of these statements ends the execution of the function and
  689. provides a value for it to return.  @xref{return Statement}.
  690. @end table
  691.  
  692. Calculating @code{fib} using ordinary integers in C works only for
  693. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  694. in type @code{int}.  The addition operation that tries to add
  695. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  696. This occurrence is called @dfn{integer overflow}.
  697.  
  698. Overflow can manifest itself in various ways, but one thing that can't
  699. possibly happen is to produce the correct value, since that can't fit
  700. in the space for the value.  @xref{Integer Overflow}.
  701.  
  702. @xref{Functions}, for a full explanation about functions.
  703.  
  704. @node Stack
  705. @section The Stack, And Stack Overflow
  706. @cindex stack
  707. @cindex stack frame
  708. @cindex stack overflow
  709. @cindex recursion, drawbacks of
  710.  
  711. @cindex stack frame
  712. Recursion has a drawback: there are limits to how many nested function
  713. calls a program can make.  In C, each function call allocates a block
  714. of memory which it uses until the call returns.  C allocates these
  715. blocks consecutively within a large area of memory known as the
  716. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  717.  
  718. The size of the stack is limited; if the program tries to use too
  719. much, that causes the program to fail because the stack is full.  This
  720. is called @dfn{stack overflow}.
  721.  
  722. @cindex crash
  723. @cindex segmentation fault
  724. Stack overflow on GNU/Linux typically manifests itself as the
  725. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  726. fault.''  By default, this signal terminates the program immediately,
  727. rather than letting the program try to recover, or reach an expected
  728. ending point.  (We commonly say in this case that the program
  729. ``crashes'').  @xref{Signals}.
  730.  
  731. It is inconvenient to observe a crash by passing too large
  732. an argument to recursive Fibonacci, because the program would run a
  733. long time before it crashes.  This algorithm is simple but
  734. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  735. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  736. the final result.
  737.  
  738. However, you can observe stack overflow very quickly if you use
  739. this function instead:
  740.  
  741. @example
  742. int
  743. fill_stack (int n)
  744. @{
  745.  if (n <= 1)  /* @r{This limits the depth of recursion.}  */
  746.    return 1;
  747.  else
  748.    return fill_stack (n - 1);
  749. @}
  750. @end example
  751.  
  752. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  753. and using the default configuration, an experiment showed there is
  754. enough stack space to do 261906 nested calls to that function.  One
  755. more, and the stack overflows and the program crashes.  On another
  756. platform, with a different configuration, or with a different
  757. function, the limit might be bigger or smaller.
  758.  
  759. @node Iterative Fibonacci
  760. @section Example: Iterative Fibonacci
  761. @cindex iterative Fibonacci function
  762. @cindex Fibonacci function, iterative
  763.  
  764. Here's a much faster algorithm for computing the same Fibonacci
  765. series.  It is faster for two reasons.  First, it uses @dfn{iteration}
  766. (that is, repetition or looping) rather than recursion, so it doesn't
  767. take time for a large number of function calls.  But mainly, it is
  768. faster because the number of repetitions is small---only @code{@var{n}}.
  769.  
  770. @c If you change this, change the duplicate in node Example of for.
  771.  
  772. @example
  773. int
  774. fib (int n)
  775. @{
  776.  int last = 1;   /* @r{Initial value is @code{fib (1)}.}  */
  777.  int prev = 0;   /* @r{Initial value controls @code{fib (2)}.}  */
  778.  int i;
  779.  
  780.  for (i = 1; i < n; ++i)
  781.    /* @r{If @code{n} is 1 or less, the loop runs zero times,}  */
  782.    /* @r{since @code{i < n} is false the first time.}  */
  783.    @{
  784.      /* @r{Now @code{last} is @code{fib (@code{i})}}
  785.         @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.}  */
  786.      /* @r{Compute @code{fib (@code{i} + 1)}.}  */
  787.      int next = prev + last;
  788.      /* @r{Shift the values down.}  */
  789.      prev = last;
  790.      last = next;
  791.      /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  792.         @r{and @code{prev} is @code{fib (@code{i})}.}
  793.         @r{But that won't stay true for long,}
  794.         @r{because we are about to increment @code{i}.}  */
  795.    @}
  796.  
  797.  return last;
  798. @}
  799. @end example
  800.  
  801. This definition computes @code{fib (@var{n})} in a time proportional
  802. to @code{@var{n}}.  The comments in the definition explain how it works: it
  803. advances through the series, always keeps the last two values in
  804. @code{last} and @code{prev}, and adds them to get the next value.
  805.  
  806. Here are the additional C features that this definition uses:
  807.  
  808. @table @asis
  809. @item Internal blocks
  810. Within a function, wherever a statement is called for, you can write a
  811. @dfn{block}.  It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  812. more statements and declarations.  (You can also use additional
  813. blocks as statements in a block.)
  814.  
  815. The function body also counts as a block, which is why it can contain
  816. statements and declarations.
  817.  
  818. @xref{Blocks}.
  819.  
  820. @item Declarations of local variables
  821. This function body contains declarations as well as statements.  There
  822. are three declarations directly in the function body, as well as a
  823. fourth declaration in an internal block.  Each starts with @code{int}
  824. because it declares a variable whose type is integer.  One declaration
  825. can declare several variables, but each of these declarations is
  826. simple and declares just one variable.
  827.  
  828. Variables declared inside a block (either a function body or an
  829. internal block) are @dfn{local variables}.  These variables exist only
  830. within that block; their names are not defined outside the block, and
  831. exiting the block deallocates their storage.  This example declares
  832. four local variables: @code{last}, @code{prev}, @code{i}, and
  833. @code{next}.
  834.  
  835. The most basic local variable declaration looks like this:
  836.  
  837. @example
  838. @var{type} @var{variablename};
  839. @end example
  840.  
  841. For instance,
  842.  
  843. @example
  844. int i;
  845. @end example
  846.  
  847. @noindent
  848. declares the local variable @code{i} as an integer.
  849. @xref{Variable Declarations}.
  850.  
  851. @item Initializers
  852. When you declare a variable, you can also specify its initial value,
  853. like this:
  854.  
  855. @example
  856. @var{type} @var{variablename} = @var{value};
  857. @end example
  858.  
  859. For instance,
  860.  
  861. @example
  862. int last = 1;
  863. @end example
  864.  
  865. @noindent
  866. declares the local variable @code{last} as an integer (type
  867. @code{int}) and starts it off with the value 1.  @xref{Initializers}.
  868.  
  869. @item Assignment
  870. Assignment: a specific kind of expression, written with the @samp{=}
  871. operator, that stores a new value in a variable or other place.  Thus,
  872.  
  873. @example
  874. @var{variable} = @var{value}
  875. @end example
  876.  
  877. @noindent
  878. is an expression that computes @code{@var{value}} and stores the value in
  879. @code{@var{variable}}.  @xref{Assignment Expressions}.
  880.  
  881. @item Expression statements
  882. An expression statement is an expression followed by a semicolon.
  883. That computes the value of the expression, then ignores the value.
  884.  
  885. An expression statement is useful when the expression changes some
  886. data or has other side effects---for instance, with function calls, or
  887. with assignments as in this example.  @xref{Expression Statement}.
  888.  
  889. Using an expression with no side effects in an expression statement is
  890. pointless except in very special cases.  For instance, the expression
  891. statement @code{x;} would examine the value of @code{x} and ignore it.
  892. That is not useful.
  893.  
  894. @item Increment operator
  895. The increment operator is @samp{++}.  @code{++i} is an
  896. expression that is short for @code{i = i + 1}.
  897. @xref{Increment/Decrement}.
  898.  
  899. @item @code{for} statements
  900. A @code{for} statement is a clean way of executing a statement
  901. repeatedly---a @dfn{loop} (@pxref{Loop Statements}).  Specifically,
  902.  
  903. @example
  904. for (i = 1; i < n; ++i)
  905.  @var{body}
  906. @end example
  907.  
  908. @noindent
  909. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  910. for the loop.  The loop itself consists of
  911.  
  912. @itemize @bullet
  913. @item
  914. Testing @code{i < n} and exiting the loop if that's false.
  915.  
  916. @item
  917. Executing @var{body}.
  918.  
  919. @item
  920. Advancing the loop (executing @code{++i}, which increments @code{i}).
  921. @end itemize
  922.  
  923. The net result is to execute @var{body} with 0 in @code{i},
  924. then with 1 in @code{i}, and so on, stopping just before the repetition
  925. where @code{i} would equal @code{n}.
  926.  
  927. The body of the @code{for} statement must be one and only one
  928. statement.  You can't write two statements in a row there; if you try
  929. to, only the first of them will be treated as part of the loop.
  930.  
  931. The way to put multiple statements in those places is to group them
  932. with a block, and that's what we do in this example.
  933. @end table
  934.  
  935. @node Complete Program
  936. @chapter A Complete Program
  937. @cindex complete example program
  938. @cindex example program, complete
  939.  
  940. It's all very well to write a Fibonacci function, but you cannot run
  941. it by itself.  It is a useful program, but it is not a complete
  942. program.
  943.  
  944. In this chapter we present a complete program that contains the
  945. @code{fib} function.  This example shows how to make the program
  946. start, how to make it finish, how to do computation, and how to print
  947. a result.
  948.  
  949. @menu
  950. * Complete Example::            Turn the simple function into a full program.
  951. * Complete Explanation::        Explanation of each part of the example.
  952. * Complete Line-by-Line::       Explaining each line of the example.
  953. * Compile Example::             Using GCC to compile the example.
  954. @end menu
  955.  
  956. @node Complete Example
  957. @section Complete Program Example
  958.  
  959. Here is the complete program that uses the simple, recursive version
  960. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  961.  
  962. @example
  963. #include <stdio.h>
  964.  
  965. int
  966. fib (int n)
  967. @{
  968.  if (n <= 2)  /* @r{This avoids infinite recursion.}  */
  969.    return 1;
  970.  else
  971.    return fib (n - 1) + fib (n - 2);
  972. @}
  973.  
  974. int
  975. main (void)
  976. @{
  977.   printf ("Fibonacci series item %d is %d\n",
  978.           20, fib (20));
  979.   return 0;
  980. @}
  981. @end example
  982.  
  983. @noindent
  984. This program prints a message that shows the value of @code{fib (20)}.
  985.  
  986. Now for an explanation of what that code means.
  987.  
  988. @node Complete Explanation
  989. @section Complete Program Explanation
  990.  
  991. @ifnottex
  992. Here's the explanation of the code of the example in the
  993. previous section.
  994. @end ifnottex
  995.  
  996. This sample program prints a message that shows the value of @code{fib
  997. (20)}, and exits with code 0 (which stands for successful execution).
  998.  
  999. Every C program is started by running the function named @code{main}.
  1000. Therefore, the example program defines a function named @code{main} to
  1001. provide a way to start it.  Whatever that function does is what the
  1002. program does.  @xref{The main Function}.
  1003.  
  1004. The @code{main} function is the first one called when the program
  1005. runs, but it doesn't come first in the example code.  The order of the
  1006. function definitions in the source code makes no difference to the
  1007. program's meaning.
  1008.  
  1009. The initial call to @code{main} always passes certain arguments, but
  1010. @code{main} does not have to pay attention to them.  To ignore those
  1011. arguments, define @code{main} with @code{void} as the parameter list.
  1012. (@code{void} as a function's parameter list normally means ``call with
  1013. no arguments,'' but @code{main} is a special case.)
  1014.  
  1015. The function @code{main} returns 0 because that is
  1016. the conventional way for @code{main} to indicate successful execution.
  1017. It could instead return a positive integer to indicate failure, and
  1018. some utility programs have specific conventions for the meaning of
  1019. certain numeric @dfn{failure codes}.  @xref{Values from main}.
  1020.  
  1021. @cindex @code{printf}
  1022. The simplest way to print text in C is by calling the @code{printf}
  1023. function, so here we explain what that does.
  1024.  
  1025. @cindex standard output
  1026. The first argument to @code{printf} is a @dfn{string constant}
  1027. (@pxref{String Constants}) that is a template for output.  The
  1028. function @code{printf} copies most of that string directly as output,
  1029. including the newline character at the end of the string, which is
  1030. written as @samp{\n}.  The output goes to the program's @dfn{standard
  1031. output} destination, which in the usual case is the terminal.
  1032.  
  1033. @samp{%} in the template introduces a code that substitutes other text
  1034. into the output.  Specifically, @samp{%d} means to take the next
  1035. argument to @code{printf} and substitute it into the text as a decimal
  1036. number.  (The argument for @samp{%d} must be of type @code{int}; if it
  1037. isn't, @code{printf} will malfunction.)  So the output is a line that
  1038. looks like this:
  1039.  
  1040. @example
  1041. Fibonacci series item 20 is 6765
  1042. @end example
  1043.  
  1044. This program does not contain a definition for @code{printf} because
  1045. it is defined by the C library, which makes it available in all C
  1046. programs.  However, each program does need to @dfn{declare}
  1047. @code{printf} so it will be called correctly.  The @code{#include}
  1048. line takes care of that; it includes a @dfn{header file} called
  1049. @file{stdio.h} into the program's code.  That file is provided by the
  1050. operating system and it contains declarations for the many standard
  1051. input/output functions in the C library, one of which is
  1052. @code{printf}.
  1053.  
  1054. Don't worry about header files for now; we'll explain them later in
  1055. @ref{Header Files}.
  1056.  
  1057. The first argument of @code{printf} does not have to be a string
  1058. constant; it can be any string (@pxref{Strings}).  However, using a
  1059. constant is the most common case.
  1060.  
  1061. To learn more about @code{printf} and other facilities of the C
  1062. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  1063. Reference Manual}.
  1064.  
  1065. @node Complete Line-by-Line
  1066. @section Complete Program, Line by Line
  1067.  
  1068. Here's the same example, explained line by line.
  1069. @strong{Beginners, do you find this helpful or not?
  1070. Would you prefer a different layout for the example?
  1071. Please tell rms@@gnu.org.}
  1072.  
  1073. @example
  1074. #include <stdio.h>      /* @r{Include declaration of usual} */
  1075.                        /*   @r{I/O functions such as @code{printf}.}  */
  1076.                        /* @r{Most programs need these.}  */
  1077.  
  1078. int                     /* @r{This function returns an @code{int}.}  */
  1079. fib (int n)             /* @r{Its name is @code{fib};}  */
  1080.                        /*   @r{its argument is called @code{n}.}  */
  1081. @{                       /* @r{Start of function body.}  */
  1082.  /* @r{This stops the recursion from being infinite.}  */
  1083.  if (n <= 2)           /* @r{If @code{n} is 1 or 2,}  */
  1084.    return 1;           /*   @r{make @code{fib} return 1.}  */
  1085.  else                  /* @r{otherwise, add the two previous}  */
  1086.                        /* @r{fibonacci numbers.}  */
  1087.    return fib (n - 1) + fib (n - 2);
  1088. @}
  1089.  
  1090. int                     /* @r{This function returns an @code{int}.}  */
  1091. main (void)             /* @r{Start here; ignore arguments.}  */
  1092. @{                       /* @r{Print message with numbers in it.}  */
  1093.   printf ("Fibonacci series item %d is %d\n",
  1094.           20, fib (20));
  1095.   return 0;             /* @r{Terminate program, report success.}  */
  1096. @}
  1097. @end example
  1098.  
  1099. @node Compile Example
  1100. @section Compiling the Example Program
  1101. @cindex compiling
  1102. @cindex executable file
  1103.  
  1104. To run a C program requires converting the source code into an
  1105. @dfn{executable file}.  This is called @dfn{compiling} the program,
  1106. and the command to do that using GNU C is @command{gcc}.
  1107.  
  1108. This example program consists of a single source file.  If we
  1109. call that file @file{fib1.c}, the complete command to compile it is
  1110. this:
  1111.  
  1112. @example
  1113. gcc -g -O -o fib1 fib1.c
  1114. @end example
  1115.  
  1116. @noindent
  1117. Here, @option{-g} says to generate debugging information, @option{-O}
  1118. says to optimize at the basic level, and @option{-o fib1} says to put
  1119. the executable program in the file @file{fib1}.
  1120.  
  1121. To run the program, use its file name as a shell command.
  1122. For instance,
  1123.  
  1124. @example
  1125. ./fib1
  1126. @end example
  1127.  
  1128. @noindent
  1129. However, unless you are sure the program is correct, you should
  1130. expect to need to debug it.  So use this command,
  1131.  
  1132. @example
  1133. gdb fib1
  1134. @end example
  1135.  
  1136. @noindent
  1137. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  1138. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  1139. debug the executable program @code{fib1}.
  1140.  
  1141.  
  1142. @xref{Compilation}, for an introduction to compiling more complex
  1143. programs which consist of more than one source file.
  1144.  
  1145. @node Storage
  1146. @chapter Storage and Data
  1147. @cindex bytes
  1148. @cindex storage organization
  1149. @cindex memory organization
  1150.  
  1151. Storage in C programs is made up of units called @dfn{bytes}.  On
  1152. nearly all computers, a byte consists of 8 bits, but there are a few
  1153. peculiar computers (mostly ``embedded controllers'' for very small
  1154. systems) where a byte is longer than that.  This manual does not try
  1155. to explain the peculiarity of those computers; we assume that a byte
  1156. is 8 bits.
  1157.  
  1158. Every C data type is made up of a certain number of bytes; that number
  1159. is the data type's @dfn{size}.  @xref{Type Size}, for details.  The
  1160. types @code{signed char} and @code{unsigned char} are one byte long;
  1161. use those types to operate on data byte by byte.  @xref{Signed and
  1162. Unsigned Types}.  You can refer to a series of consecutive bytes as an
  1163. array of @code{char} elements; that's what an ASCII string looks like
  1164. in memory.  @xref{String Constants}.
  1165.  
  1166. @node Beyond Integers
  1167. @chapter Beyond Integers
  1168.  
  1169. So far we've presented programs that operate on integers.  In this
  1170. chapter we'll present examples of handling non-integral numbers and
  1171. arrays of numbers.
  1172.  
  1173. @menu
  1174. * Float Example::       A function that uses floating-point numbers.
  1175. * Array Example::       A function that works with arrays.
  1176. * Array Example Call::  How to call that function.
  1177. * Array Example Variations::   Different ways to write the call example.
  1178. @end menu
  1179.  
  1180. @node Float Example
  1181. @section An Example with Non-Integer Numbers
  1182. @cindex floating point example
  1183.  
  1184. Here's a function that operates on and returns @dfn{floating point}
  1185. numbers that don't have to be integers.  Floating point represents a
  1186. number as a fraction together with a power of 2.  (For more detail,
  1187. @pxref{Floating-Point Data Types}.)  This example calculates the
  1188. average of three floating point numbers that are passed to it as
  1189. arguments:
  1190.  
  1191. @example
  1192. double
  1193. average_of_three (double a, double b, double c)
  1194. @{
  1195.  return (a + b + c) / 3;
  1196. @}
  1197. @end example
  1198.  
  1199. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  1200. integers, and even when they happen to be integers, most likely their
  1201. average is not an integer.
  1202.  
  1203. @code{double} is the usual data type in C for calculations on
  1204. floating-point numbers.
  1205.  
  1206. To print a @code{double} with @code{printf}, we must use @samp{%f}
  1207. instead of @samp{%d}:
  1208.  
  1209. @example
  1210. printf ("Average is %f\n",
  1211.         average_of_three (1.1, 9.8, 3.62));
  1212. @end example
  1213.  
  1214. The code that calls @code{printf} must pass a @code{double} for
  1215. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  1216. If the argument has the wrong type, @code{printf} will produce garbage
  1217. output.
  1218.  
  1219. Here's a complete program that computes the average of three
  1220. specific numbers and prints the result:
  1221.  
  1222. @example
  1223. double
  1224. average_of_three (double a, double b, double c)
  1225. @{
  1226.  return (a + b + c) / 3;
  1227. @}
  1228.  
  1229. int
  1230. main (void)
  1231. @{
  1232.     printf ("Average is %f\n",
  1233.             average_of_three (1.1, 9.8, 3.62));
  1234.     return 0;
  1235. @}
  1236. @end example
  1237.  
  1238. From now on we will not present examples of calls to @code{main}.
  1239. Instead we encourage you to write them for yourself when you want
  1240. to test executing some code.
  1241.  
  1242. @node Array Example
  1243. @section An Example with Arrays
  1244. @cindex array example
  1245.  
  1246. A function to take the average of three numbers is very specific and
  1247. limited.  A more general function would take the average of any number
  1248. of numbers.  That requires passing the numbers in an array.  An array
  1249. is an object in memory that contains a series of values of the same
  1250. data type.  This chapter presents the basic concepts and use of arrays
  1251. through an example; for the full explanation, see @ref{Arrays}.
  1252.  
  1253. Here's a function definition to take the average of several
  1254. floating-point numbers, passed as type @code{double}.  The first
  1255. parameter, @code{length}, specifies how many numbers are passed.  The
  1256. second parameter, @code{input_data}, is an array that holds those
  1257. numbers.
  1258.  
  1259. @example
  1260. double
  1261. avg_of_double (int length, double input_data[])
  1262. @{
  1263.  double sum = 0;
  1264.  int i;
  1265.  for (i = 0; i < length; i++)
  1266.    sum = sum + input_data[i];
  1267.  
  1268.  return sum / length;
  1269. @}
  1270. @end example
  1271.  
  1272. This introduces the expression to refer to an element of an array:
  1273. @code{input_data[i]} means the element at index @code{i} in
  1274. @code{input_data}.  The index of the element can be any expression
  1275. with an integer value; in this case, the expression is @code{i}.
  1276. @xref{Accessing Array Elements}.
  1277.  
  1278. @cindex zero-origin indexing
  1279. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1280. valid index is one less than the number of elements.  (This is known
  1281. as @dfn{zero-origin indexing}.)
  1282.  
  1283. This example also introduces the way to declare that a function
  1284. parameter is an array.  Such declarations are modeled after the syntax
  1285. for an element of the array.  Just as @code{double foo} declares that
  1286. @code{foo} is of type @code{double}, @code{double input_data[]}
  1287. declares that each element of @code{input_data} is of type
  1288. @code{double}.  Therefore, @code{input_data} itself has type ``array
  1289. of @code{double}.''
  1290. When declaring an array parameter, it's not necessary to say how long
  1291. the array is.  In this case, the parameter @code{input_data} has no
  1292. length information.  That's why the function needs another parameter,
  1293. @code{length}, for the caller to provide that information to the
  1294. function @code{avg_of_double}.
  1295. @node Array Example Call
  1296. @section Calling the Array Example
  1297. To call the function @code{avg_of_double} requires making an
  1298. array and then passing it as an argument.  Here is an example.
  1299. @example
  1300. @{
  1301.  /* @r{The array of values to average.}  */
  1302.  double nums_to_average[5];
  1303.  /* @r{The average, once we compute it.}  */
  1304.  double average;
  1305.  
  1306.  /* @r{Fill in elements of @code{nums_to_average}.}  */
  1307.  
  1308.  nums_to_average[0] = 58.7;
  1309.  nums_to_average[1] = 5.1;
  1310.  nums_to_average[2] = 7.7;
  1311.  nums_to_average[3] = 105.2;
  1312.  nums_to_average[4] = -3.14159;
  1313.  
  1314.  average = avg_of_double (5, nums_to_average);
  1315.  
  1316.  /* @r{@dots{}now make use of @code{average}@dots{}} */
  1317. @}
  1318. @end example
  1319.  
  1320. This shows an array subscripting expression again, this time
  1321. on the left side of an assignment, storing a value into an
  1322. element of an array.
  1323.  
  1324. It also shows how to declare a local variable that is an array:
  1325. @code{double nums_to_average[5];}.  Since this declaration allocates the
  1326. space for the array, it needs to know the array's length.  You can
  1327. specify the length with any expression whose value is an integer, but
  1328. in this declaration the length is a constant, the integer 5.
  1329.  
  1330. The name of the array, when used by itself as an expression, stands
  1331. for the address of the array's data, and that's what gets passed to
  1332. the function @code{avg_of_double} in @code{avg_of_double (5,
  1333. nums_to_average)}.
  1334.  
  1335. We can make the code easier to maintain by avoiding the need to write
  1336. 5, the array length, when calling @code{avg_of_double}.  That way, if
  1337. we change the array to include more elements, we won't have to change
  1338. that call.  One way to do this is with the @code{sizeof} operator:
  1339.  
  1340. @example
  1341.  average = avg_of_double ((sizeof (nums_to_average)
  1342.                            / sizeof (nums_to_average[0])),
  1343.                           nums_to_average);
  1344. @end example
  1345.  
  1346. This computes the number of elements in @code{nums_to_average} by dividing
  1347. its total size by the size of one element.  @xref{Type Size}, for more
  1348. details of using @code{sizeof}.
  1349.  
  1350. We don't show in this example what happens after storing the result of
  1351. @code{avg_of_double} in the variable @code{average}.  Presumably
  1352. more code would follow that uses that result somehow.  (Why compute
  1353. the average and not use it?)  But that isn't part of this topic.
  1354.  
  1355. @node Array Example Variations
  1356. @section Variations for Array Example
  1357.  
  1358. The code to call @code{avg_of_double} has two declarations that
  1359. start with the same data type:
  1360.  
  1361. @example
  1362.  /* @r{The array of values to average.}  */
  1363.  double nums_to_average[5];
  1364.  /* @r{The average, once we compute it.}  */
  1365.  double average;
  1366. @end example
  1367.  
  1368. In C, you can combine the two, like this:
  1369.  
  1370. @example
  1371.  double nums_to_average[5], average;
  1372. @end example
  1373.  
  1374. This declares @code{nums_to_average} so each of its elements is a
  1375. @code{double}, and @code{average} so that it simply is a
  1376. @code{double}.
  1377.  
  1378. However, while you @emph{can} combine them, that doesn't mean you
  1379. @emph{should}.  If it is useful to write comments about the variables,
  1380. and usually it is, then it's clearer to keep the declarations separate
  1381. so you can put a comment on each one.
  1382.  
  1383. We set all of the elements of the array @code{nums_to_average} with
  1384. assignments, but it is more convenient to use an initializer in the
  1385. declaration:
  1386.  
  1387. @example
  1388. @{
  1389.  /* @r{The array of values to average.}  */
  1390.  double nums_to_average[]
  1391.    = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1392.  /* @r{The average, once we compute it.}  */
  1393.  average = avg_of_double ((sizeof (nums_to_average)
  1394.                            / sizeof (nums_to_average[0])),
  1395.                           nums_to_average);
  1396.  
  1397.  /* @r{@dots{}now make use of @code{average}@dots{}} */
  1398. @}
  1399. @end example
  1400.  
  1401. The array initializer is a comma-separated list of values, delimited
  1402. by braces.  @xref{Initializers}.
  1403.  
  1404. Note that the declaration does not specify a size for
  1405. @code{nums_to_average}, so the size is determined from the
  1406. initializer.  There are five values in the initializer, so
  1407. @code{nums_to_average} gets length 5.  If we add another element to
  1408. the initializer, @code{nums_to_average} will have six elements.
  1409.  
  1410. Because the code computes the number of elements from the size of
  1411. the array, using @code{sizeof}, the program will operate on all the
  1412. elements in the initializer, regardless of how many those are.
  1413.  
  1414. @node Lexical Syntax
  1415. @chapter Lexical Syntax
  1416. @cindex lexical syntax
  1417. @cindex token
  1418.  
  1419. To start the full description of the C language, we explain the
  1420. lexical syntax and lexical units of C code.  The lexical units of a
  1421. programming language are known as @dfn{tokens}.  This chapter covers
  1422. all the tokens of C except for constants, which are covered in a later
  1423. chapter (@pxref{Constants}).  One vital kind of token is the
  1424. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1425. kind.
  1426.  
  1427. @menu
  1428. * English::             Write programs in English!
  1429. * Characters::          The characters allowed in C programs.
  1430. * Whitespace::          The particulars of whitespace characters.
  1431. * Comments::            How to include comments in C code.
  1432. * Identifiers::         How to form identifiers (names).
  1433. * Operators/Punctuation::  Characters used as operators or punctuation.
  1434. * Line Continuation::   Splitting one line into multiple lines.
  1435. @end menu
  1436.  
  1437. @node English
  1438. @section Write Programs in English!
  1439.  
  1440. In principle, you can write the function and variable names in a
  1441. program, and the comments, in any human language.  C allows any kinds
  1442. of characters in comments, and you can put non-ASCII characters into
  1443. identifiers with a special prefix.  However, to enable programmers in
  1444. all countries to understand and develop the program, it is best given
  1445. today's circumstances to write identifiers and comments in
  1446. English.
  1447.  
  1448. English is the one language that programmers in all countries
  1449. generally study.  If a program's names are in English, most
  1450. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1451. understand them.  Most programmers in those countries can speak
  1452. English, or at least read it, but they do not read each other's
  1453. languages at all.  In India, with so many languages, two programmers
  1454. may have no common language other than English.
  1455.  
  1456. If you don't feel confident in writing English, do the best you can,
  1457. and follow each English comment with a version in a language you
  1458. write better; add a note asking others to translate that to English.
  1459. Someone will eventually do that.
  1460.  
  1461. The program's user interface is a different matter.  We don't need to
  1462. choose one language for that; it is easy to support multiple languages
  1463. and let each user choose the language to use.  This requires writing
  1464. the program to support localization of its interface.  (The
  1465. @code{gettext} package exists to support this; @pxref{Message
  1466. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1467. Manual}.)  Then a community-based translation effort can provide
  1468. support for all the languages users want to use.
  1469.  
  1470. @node Characters
  1471. @section Characters
  1472. @cindex character set
  1473. @cindex Unicode
  1474.  
  1475. @c ??? How to express ¶?
  1476.  
  1477. GNU C source files are usually written in the
  1478. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1479. was defined in the 1960s for English.  However, they can also include
  1480. Unicode characters represented in the
  1481. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1482. This makes it possible to represent accented letters such as @samp{á},
  1483. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1484. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1485. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1486. manual.}
  1487.  
  1488. In C source code, non-ASCII characters are valid in comments, in wide
  1489. character constants (@pxref{Wide Character Constants}), and in string
  1490. constants (@pxref{String Constants}).
  1491.  
  1492. @c ??? valid in identifiers?
  1493. Another way to specify non-ASCII characters in constants (character or
  1494. string) and identifiers is with an escape sequence starting with
  1495. backslash, specifying the intended Unicode character.  (@xref{Unicode
  1496. Character Codes}.)  This specifies non-ASCII characters without
  1497. putting a real non-ASCII character in the source file itself.
  1498.  
  1499. C accepts two-character aliases called @dfn{digraphs} for certain
  1500. characters.  @xref{Digraphs}.
  1501.  
  1502. @node Whitespace
  1503. @section Whitespace
  1504. @cindex whitespace characters in source files
  1505. @cindex space character in source
  1506. @cindex tab character in source
  1507. @cindex formfeed in source
  1508. @cindex linefeed in source
  1509. @cindex newline in source
  1510. @cindex carriage return in source
  1511. @cindex vertical tab in source
  1512.  
  1513. Whitespace means characters that exist in a file but appear blank in a
  1514. printed listing of a file (or traditionally did appear blank, several
  1515. decades ago).  The C language requires whitespace in order to separate
  1516. two consecutive identifiers, or to separate an identifier from a
  1517. numeric constant.  Other than that, and a few special situations
  1518. described later, whitespace is optional; you can put it in when you
  1519. wish, to make the code easier to read.
  1520.  
  1521. Space and tab in C code are treated as whitespace characters.  So are
  1522. line breaks.  You can represent a line break with the newline
  1523. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1524. the CRLF sequence (two characters: carriage return followed by a
  1525. newline character).
  1526.  
  1527. The @dfn{formfeed} character, Control-L, was traditionally used to
  1528. divide a file into pages.  It is still used this way in source code,
  1529. and the tools that generate nice printouts of source code still start
  1530. a new page after each ``formfeed'' character.  Dividing code into
  1531. pages separated by formfeed characters is a good way to break it up
  1532. into comprehensible pieces and show other programmers where they start
  1533. and end.
  1534.  
  1535. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1536. make printing advance down to the next section of a page.  We know of
  1537. no particular reason to use it in source code, but it is still
  1538. accepted as whitespace in C.
  1539.  
  1540. Comments are also syntactically equivalent to whitespace.
  1541. @ifinfo
  1542. @xref{Comments}.
  1543. @end ifinfo
  1544.  
  1545. @node Comments
  1546. @section Comments
  1547. @cindex comments
  1548.  
  1549. A comment encapsulates text that has no effect on the program's
  1550. execution or meaning.
  1551.  
  1552. The purpose of comments is to explain the code to people that read it.
  1553. Writing good comments for your code is tremendously important---they
  1554. should provide background information that helps programmers
  1555. understand the reasons why the code is written the way it is.  You,
  1556. returning to the code six months from now, will need the help of these
  1557. comments to remember why you wrote it this way.
  1558.  
  1559. Outdated comments that become incorrect are counterproductive, so part
  1560. of the software developer's responsibility is to update comments as
  1561. needed to correspond with changes to the program code.
  1562.  
  1563. C allows two kinds of comment syntax, the traditional style and the
  1564. C@t{++} style.  A traditional C comment starts with @samp{/*} and ends
  1565. with @samp{*/}.  For instance,
  1566.  
  1567. @example
  1568. /* @r{This is a comment in traditional C syntax.} */
  1569. @end example
  1570.  
  1571. A traditional comment can contain @samp{/*}, but these delimiters do
  1572. not nest as pairs.  The first @samp{*/} ends the comment regardless of
  1573. whether it contains @samp{/*} sequences.
  1574.  
  1575. @example
  1576. /* @r{This} /* @r{is a comment} */ But this is not! */
  1577. @end example
  1578.  
  1579. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1580. For instance,
  1581.  
  1582. @example
  1583. // @r{This is a comment in C@t{++} style.}
  1584. @end example
  1585.  
  1586. Line comments do nest, in effect, because @samp{//} inside a line
  1587. comment is part of that comment:
  1588.  
  1589. @example
  1590. // @r{this whole line is} // @r{one comment}
  1591. This is code, not comment.
  1592. @end example
  1593.  
  1594. It is safe to put line comments inside block comments, or vice versa.
  1595.  
  1596. @example
  1597. @group
  1598. /* @r{traditional comment}
  1599.   // @r{contains line comment}
  1600.   @r{more traditional comment}
  1601. */ text here is not a comment
  1602.  
  1603. // @r{line comment} /* @r{contains traditional comment} */
  1604. @end group
  1605. @end example
  1606.  
  1607. But beware of commenting out one end of a traditional comment with a line
  1608. comment.  The delimiter @samp{/*} doesn't start a comment if it occurs
  1609. inside an already-started comment.
  1610.  
  1611. @example
  1612. @group
  1613. // @r{line comment}  /* @r{That would ordinarily begin a block comment.}
  1614.    Oops! The line comment has ended;
  1615.    this isn't a comment any more.  */
  1616. @end group
  1617. @end example
  1618.  
  1619. Comments are not recognized within string constants.  @t{@w{"/* blah
  1620. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1621. string.
  1622.  
  1623. In this manual we show the text in comments in a variable-width font,
  1624. for readability, but this font distinction does not exist in source
  1625. files.
  1626.  
  1627. A comment is syntactically equivalent to whitespace, so it always
  1628. separates tokens.  Thus,
  1629.  
  1630. @example
  1631. @group
  1632.  int/* @r{comment} */foo;
  1633. @r{is equivalent to}
  1634.  int foo;
  1635. @end group
  1636. @end example
  1637.  
  1638. @noindent
  1639. but clean code always uses real whitespace to separate the comment
  1640. visually from surrounding code.
  1641.  
  1642. @node Identifiers
  1643. @section Identifiers
  1644. @cindex identifiers
  1645.  
  1646. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1647. as well as @samp{_}, that does not start with a digit.  Most compilers
  1648. also allow @samp{$}.  An identifier can be as long as you like; for
  1649. example,
  1650.  
  1651. @example
  1652. int anti_dis_establishment_arian_ism;
  1653. @end example
  1654.  
  1655. @cindex case of letters in identifiers
  1656. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1657. and @code{A} are two different identifiers.
  1658.  
  1659. @cindex keyword
  1660. @cindex reserved words
  1661. Identifiers in C are used as variable names, function names, typedef
  1662. names, enumeration constants, type tags, field names, and labels.
  1663. Certain identifiers in C are @dfn{keywords}, which means they have
  1664. specific syntactic meanings.  Keywords in C are @dfn{reserved words},
  1665. meaning you cannot use them in any other way.  For instance, you can't
  1666. define a variable or function named @code{return} or @code{if}.
  1667.  
  1668. You can also include other characters, even non-ASCII characters, in
  1669. identifiers by writing their Unicode character names, which start with
  1670. @samp{\u} or @samp{\U}, in the identifier name.  @xref{Unicode
  1671. Character Codes}.  However, it is usually a bad idea to use non-ASCII
  1672. characters in identifiers, and when they are written in English, they
  1673. never need non-ASCII characters.  @xref{English}.
  1674.  
  1675. Whitespace is required to separate two consecutive identifiers, or to
  1676. separate an identifier from a preceding or following numeric
  1677. constant.
  1678.  
  1679. @node Operators/Punctuation
  1680. @section Operators and Punctuation
  1681. @cindex operators
  1682. @cindex punctuation
  1683.  
  1684. Here we describe the lexical syntax of operators and punctuation in C.
  1685. The specific operators of C and their meanings are presented in
  1686. subsequent chapters.
  1687.  
  1688. Most operators in C consist of one or two characters that can't be
  1689. used in identifiers.  The characters used for operators in C are
  1690. @samp{!~^&|*/%+-=<>,.?:}.
  1691.  
  1692. Some operators are a single character.  For instance, @samp{-} is the
  1693. operator for negation (with one operand) and the operator for
  1694. subtraction (with two operands).
  1695.  
  1696. Some operators are two characters.  For example, @samp{++} is the
  1697. increment operator.  Recognition of multicharacter operators works by
  1698. grouping together as many consecutive characters as can constitute one
  1699. operator.
  1700.  
  1701. For instance, the character sequence @samp{++} is always interpreted
  1702. as the increment operator; therefore, if we want to write two
  1703. consecutive instances of the operator @samp{+}, we must separate them
  1704. with a space so that they do not combine as one token.  Applying the
  1705. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1706. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1707. of a valid C program and the former could not (since @code{a++}
  1708. is not an lvalue and thus can't be the operand of @code{++}).
  1709.  
  1710. A few C operators are keywords rather than special characters.  They
  1711. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1712. (@pxref{Type Alignment}).
  1713.  
  1714. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1715. Semicolon (@samp{;}) ends a statement.  Braces (@samp{@{} and
  1716. @samp{@}}) begin and end a block at the statement level
  1717. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1718. for a variable with multiple elements or components (such as arrays or
  1719. structures).
  1720. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1721. @code{array[5]}.
  1722.  
  1723. Parentheses are used in expressions for explicit nesting of
  1724. expressions (@pxref{Basic Arithmetic}), around the parameter
  1725. declarations in a function declaration or definition, and around the
  1726. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1727. (@pxref{Function Calls}).  Several kinds of statements also use
  1728. parentheses as part of their syntax---for instance, @code{if}
  1729. statements, @code{for} statements, @code{while} statements, and
  1730. @code{switch} statements.  @xref{if Statement}, and following
  1731. sections.
  1732.  
  1733. Parentheses are also required around the operand of the operator
  1734. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1735. type rather than a value.  @xref{Type Size}.
  1736.  
  1737. @node Line Continuation
  1738. @section Line Continuation
  1739. @cindex line continuation
  1740. @cindex continuation of lines
  1741.  
  1742. The sequence of a backslash and a newline is ignored absolutely
  1743. anywhere in a C program.  This makes it possible to split a single
  1744. source line into multiple lines in the source file.  GNU C tolerates
  1745. and ignores other whitespace between the backslash and the newline.
  1746. In particular, it always ignores a CR (carriage return) character
  1747. there, in case some text editor decided to end the line with the CRLF
  1748. sequence.
  1749.  
  1750. The main use of line continuation in C is for macro definitions that
  1751. would be inconveniently long for a single line (@pxref{Macros}).
  1752.  
  1753. It is possible to continue a line comment onto another line with
  1754. backslash-newline.  You can put backslash-newline in the middle of an
  1755. identifier, even a keyword, or an operator.  You can even split
  1756. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1757. backslash-newline.  Here's an ugly example:
  1758.  
  1759. @example
  1760. @group
  1761. /\
  1762. *
  1763. */ fo\
  1764. o +\
  1765. = 1\
  1766. 0;
  1767. @end group
  1768. @end example
  1769.  
  1770. @noindent
  1771. That's equivalent to @samp{/* */ foo += 10;}.
  1772.  
  1773. Don't do those things in real programs, since they make code hard to
  1774. read.
  1775.  
  1776. @strong{Note:} For the sake of using certain tools on the source code, it is
  1777. wise to end every source file with a newline character which is not
  1778. preceded by a backslash, so that it really ends the last line.
  1779.  
  1780. @node Arithmetic
  1781. @chapter Arithmetic
  1782. @cindex arithmetic operators
  1783. @cindex operators, arithmetic
  1784.  
  1785. @c ??? Duplication with other sections -- get rid of that?
  1786.  
  1787. Arithmetic operators in C attempt to be as similar as possible to the
  1788. abstract arithmetic operations, but it is impossible to do this
  1789. perfectly.  Numbers in a computer have a finite range of possible
  1790. values, and non-integer values have a limit on their possible
  1791. accuracy.  Nonetheless, in most cases you will encounter no surprises
  1792. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1793. for multiplication.
  1794.  
  1795. Each C operator has a @dfn{precedence}, which is its rank in the
  1796. grammatical order of the various operators.  The operators with the
  1797. highest precedence grab adjoining operands first; these expressions
  1798. then become operands for operators of lower precedence.  We give some
  1799. information about precedence of operators in this chapter where we
  1800. describe the operators; for the full explanation, see @ref{Binary
  1801. Operator Grammar}.
  1802.  
  1803. The arithmetic operators always @dfn{promote} their operands before
  1804. operating on them.  This means converting narrow integer data types to
  1805. a wider data type (@pxref{Operand Promotions}).  If you are just
  1806. learning C, don't worry about this yet.
  1807.  
  1808. Given two operands that have different types, most arithmetic
  1809. operations convert them both to their @dfn{common type}.  For
  1810. instance, if one is @code{int} and the other is @code{double}, the
  1811. common type is @code{double}.  (That's because @code{double} can
  1812. represent all the values that an @code{int} can hold, but not vice
  1813. versa.)  For the full details, see @ref{Common Type}.
  1814.  
  1815. @menu
  1816. * Basic Arithmetic::       Addition, subtraction, multiplication,
  1817.                             and division.
  1818. * Integer Arithmetic::     How C performs arithmetic with integer values.
  1819. * Integer Overflow::       When an integer value exceeds the range
  1820.                             of its type.
  1821. * Mixed Mode::             Calculating with both integer values
  1822.                             and floating-point values.
  1823. * Division and Remainder:: How integer division works.
  1824. * Numeric Comparisons::    Comparing numeric values for equality or order.
  1825. * Shift Operations::       Shift integer bits left or right.
  1826. * Bitwise Operations::     Bitwise conjunction, disjunction, negation.
  1827. @end menu
  1828.  
  1829. @node Basic Arithmetic
  1830. @section Basic Arithmetic
  1831. @cindex addition operator
  1832. @cindex subtraction operator
  1833. @cindex multiplication operator
  1834. @cindex division operator
  1835. @cindex negation operator
  1836. @cindex operator, addition
  1837. @cindex operator, subtraction
  1838. @cindex operator, multiplication
  1839. @cindex operator, division
  1840. @cindex operator, negation
  1841.  
  1842. Basic arithmetic in C is done with the usual binary operators of
  1843. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1844. (@samp{*}) and division (@samp{/}).  The unary operator @samp{-} is
  1845. used to change the sign of a number.  The unary @code{+} operator also
  1846. exists; it yields its operand unaltered.
  1847.  
  1848. @samp{/} is the division operator, but dividing integers may not give
  1849. the result you expect.  Its value is an integer, which is not equal to
  1850. the mathematical quotient when that is a fraction.  Use @samp{%} to
  1851. get the corresponding integer remainder when necessary.
  1852. @xref{Division and Remainder}.  Floating point division yields value
  1853. as close as possible to the mathematical quotient.
  1854.  
  1855. These operators use algebraic syntax with the usual algebraic
  1856. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1857. and division are done before addition and subtraction, but you can use
  1858. parentheses to explicitly specify how the operators nest.  They are
  1859. left-associative (@pxref{Associativity and Ordering}).  Thus,
  1860.  
  1861. @example
  1862. -a + b - c + d * e / f
  1863. @end example
  1864.  
  1865. @noindent
  1866. is equivalent to
  1867.  
  1868. @example
  1869. (((-a) + b) - c) + ((d * e) / f)
  1870. @end example
  1871.  
  1872. @node Integer Arithmetic
  1873. @section Integer Arithmetic
  1874. @cindex integer arithmetic
  1875.  
  1876. Each of the basic arithmetic operations in C has two variants for
  1877. integers: @dfn{signed} and @dfn{unsigned}.  The choice is determined
  1878. by the data types of their operands.
  1879.  
  1880. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1881. A signed type can hold a range of positive and negative numbers, with
  1882. zero near the middle of the range.  An unsigned type can hold only
  1883. nonnegative numbers; its range starts with zero and runs upward.
  1884.  
  1885. The most basic integer types are @code{int}, which normally can hold
  1886. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1887. int}, which normally can hold numbers from 0 to 4,294.967,295.  (This
  1888. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1889. computers but not always on embedded controllers.)  @xref{Integer
  1890. Types}, for full information about integer types.
  1891.  
  1892. When a basic arithmetic operation is given two signed operands, it
  1893. does signed arithmetic.  Given two unsigned operands, it does
  1894. unsigned arithmetic.
  1895.  
  1896. If one operand is @code{unsigned int} and the other is @code{int}, the
  1897. operator treats them both as unsigned.  More generally, the common
  1898. type of the operands determines whether the operation is signed or
  1899. not.  @xref{Common Type}.
  1900.  
  1901. Printing the results of unsigned arithmetic with @code{printf} using
  1902. @samp{%d} can produce surprising results for values far away from
  1903. zero.  Even though the rules above say that the computation was done
  1904. with unsigned arithmetic, the printed result may appear to be signed!
  1905.  
  1906. The explanation is that the bit pattern resulting from addition,
  1907. subtraction or multiplication is actually the same for signed and
  1908. unsigned operations.  The difference is only in the data type of the
  1909. result, which affects the @emph{interpretation} of the result bit pattern,
  1910. and whether the arithmetic operation can overflow (see the next section).
  1911.  
  1912. But @samp{%d} doesn't know its argument's data type.  It sees only the
  1913. value's bit pattern, and it is defined to interpret that as
  1914. @code{signed int}.  To print it as unsigned requires using @samp{%u}
  1915. instead of @samp{%d}.  @xref{Formatted Output, The GNU C Library, ,
  1916. libc, The GNU C Library Reference Manual}.
  1917.  
  1918. Arithmetic in C never operates directly on narrow integer types (those
  1919. with fewer bits than @code{int}; @ref{Narrow Integers}).  Instead it
  1920. ``promotes'' them to @code{int}.  @xref{Operand Promotions}.
  1921.  
  1922. @node Integer Overflow
  1923. @section Integer Overflow
  1924. @cindex integer overflow
  1925. @cindex overflow, integer
  1926.  
  1927. When the mathematical value of an arithmetic operation doesn't fit in
  1928. the range of the data type in use, that's called @dfn{overflow}.
  1929. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1930.  
  1931. Integer overflow happens only in arithmetic operations.  Type conversion
  1932. operations, by definition, do not cause overflow, not even when the
  1933. result can't fit in its new type.  @xref{Integer Conversion}.
  1934.  
  1935. Signed numbers use two's-complement representation, in which the most
  1936. negative number lacks a positive counterpart (@pxref{Integers in
  1937. Depth}).  Thus, the unary @samp{-} operator on a signed integer can
  1938. overflow.
  1939.  
  1940. @menu
  1941. * Unsigned Overflow::           Overlow in unsigned integer arithmetic.
  1942. * Signed Overflow::             Overlow in signed integer arithmetic.
  1943. @end menu
  1944.  
  1945. @node Unsigned Overflow
  1946. @subsection Overflow with Unsigned Integers
  1947.  
  1948. Unsigned arithmetic in C ignores overflow; it produces the true result
  1949. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1950. in the data type.  We say it ``truncates'' the true result to the
  1951. lowest @var{n} bits.
  1952.  
  1953. A true result that is negative, when taken modulo the @var{n}th power
  1954. of 2, yields a positive number.  For instance,
  1955.  
  1956. @example
  1957. unsigned int x = 1;
  1958. unsigned int y;
  1959.  
  1960. y = -x;
  1961. @end example
  1962.  
  1963. @noindent
  1964. causes overflow because the negative number @minus{}1 can't be stored
  1965. in an unsigned type.  The actual result, which is @minus{}1 modulo the
  1966. @var{n}th power of 2, is one less than the @var{n}th power of 2.  That
  1967. is the largest value that the unsigned data type can store.  For a
  1968. 32-bit @code{unsigned int}, the value is 4,294,967,295.  @xref{Maximum
  1969. and Minimum Values}.
  1970.  
  1971. Adding that number to itself, as here,
  1972.  
  1973. @example
  1974. unsigned int z;
  1975.  
  1976. z = y + y;
  1977. @end example
  1978.  
  1979. @noindent
  1980. ought to yield 8,489,934,590; however, that is again too large to fit,
  1981. so overflow truncates the value to 4,294,967,294.  If that were a
  1982. signed integer, it would mean @minus{}2, which (not by coincidence)
  1983. equals @minus{}1 + @minus{}1.
  1984.  
  1985. @node Signed Overflow
  1986. @subsection Overflow with Signed Integers
  1987. @cindex compiler options for integer overflow
  1988. @cindex integer overflow, compiler options
  1989. @cindex overflow, compiler options
  1990.  
  1991. For signed integers, the result of overflow in C is @emph{in
  1992. principle} undefined, meaning that anything whatsoever could happen.
  1993. Therefore, C compilers can do optimizations that treat the overflow
  1994. case with total unconcern.  (Since the result of overflow is undefined
  1995. in principle, one cannot claim that these optimizations are
  1996. erroneous.)
  1997.  
  1998. @strong{Watch out:} These optimizations can do surprising things.  For
  1999. instance,
  2000.  
  2001. @example
  2002. int i;
  2003. @r{@dots{}}
  2004. if (i < i + 1)
  2005.  x = 5;
  2006. @end example
  2007.  
  2008. @noindent
  2009. could be optimized to do the assignment unconditionally, because the
  2010. @code{if}-condition is always true if @code{i + 1} does not overflow.
  2011.  
  2012. GCC offers compiler options to control handling signed integer
  2013. overflow.  These options operate per module; that is, each module
  2014. behaves according to the options it was compiled with.
  2015.  
  2016. These two options specify particular ways to handle signed integer
  2017. overflow, other than the default way:
  2018.  
  2019. @table @option
  2020. @item -fwrapv
  2021. Make signed integer operations well-defined, like unsigned integer
  2022. operations: they produce the @var{n} low-order bits of the true
  2023. result.  The highest of those @var{n} bits is the sign bit of the
  2024. result.  With @option{-fwrapv}, these out-of-range operations are not
  2025. considered overflow, so (strictly speaking) integer overflow never
  2026. happens.
  2027.  
  2028. The option @option{-fwrapv} enables some optimizations based on the
  2029. defined values of out-of-range results.  In GCC 8, it disables
  2030. optimizations that are based on assuming signed integer operations
  2031. will not overflow.
  2032.  
  2033. @item -ftrapv
  2034. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  2035. This terminates the program unless the program handles the signal.
  2036. @xref{Signals}.
  2037. @end table
  2038.  
  2039. One other option is useful for finding where overflow occurs:
  2040.  
  2041. @ignore
  2042. @item -fno-strict-overflow
  2043. Disable optimizations that are based on assuming signed integer
  2044. operations will not overflow.
  2045. @end ignore
  2046.  
  2047. @table @option
  2048. @item -fsanitize=signed-integer-overflow
  2049. Output a warning message at run time when signed integer overflow
  2050. occurs.  This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  2051. This takes priority over @option{-ftrapv}.
  2052. @end table
  2053.  
  2054. @node Mixed Mode
  2055. @section Mixed-Mode Arithmetic
  2056.  
  2057. Mixing integers and floating-point numbers in a basic arithmetic
  2058. operation converts the integers automatically to floating point.
  2059. In most cases, this gives exactly the desired results.
  2060. But sometimes it matters precisely where the conversion occurs.
  2061.  
  2062. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  2063. as an integer, then converts the sum to floating point for the
  2064. multiplication.  If the addition gets an overflow, that is not
  2065. equivalent to converting both integers to floating point and then
  2066. adding them.  You can get the latter result by explicitly converting
  2067. the integers, as in @code{((double) i + (double) j) * 2.0}.
  2068. @xref{Explicit Type Conversion}.
  2069.  
  2070. @c Eggert's report
  2071. Adding or multiplying several values, including some integers and some
  2072. floating point, does the operations left to right.  Thus, @code{3.0 +
  2073. i + j} converts @code{i} to floating point, then adds 3.0, then
  2074. converts @code{j} to floating point and adds that.  You can specify a
  2075. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  2076. and @code{j} first and then adds that result (converting to floating
  2077. point) to 3.0.  In this respect, C differs from other languages, such
  2078. as Fortran.
  2079.  
  2080. @node Division and Remainder
  2081. @section Division and Remainder
  2082. @cindex remainder operator
  2083. @cindex modulus
  2084. @cindex operator, remainder
  2085.  
  2086. Division of integers in C rounds the result to an integer.  The result
  2087. is always rounded towards zero.
  2088.  
  2089. @example
  2090. 16 / 3  @result{} 5
  2091. -16 / 3  @result{} -5
  2092. 16 / -3 @result{} -5
  2093. -16 / -3 @result{} 5
  2094. @end example
  2095.  
  2096. @noindent
  2097. To get the corresponding remainder, use the @samp{%} operator:
  2098.  
  2099. @example
  2100.  16 % 3  @result{} 1
  2101. -16 % 3  @result{} -1
  2102.  16 % -3 @result{} 1
  2103. -16 % -3 @result{} -1
  2104. @end example
  2105.  
  2106. @noindent
  2107. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  2108.  
  2109. From the rounded quotient and the remainder, you can reconstruct
  2110. the dividend, like this:
  2111.  
  2112. @example
  2113. int
  2114. original_dividend (int divisor, int quotient, int remainder)
  2115. @{
  2116.  return divisor * quotient + remainder;
  2117. @}
  2118. @end example
  2119.  
  2120. To do unrounded division, use floating point.  If only one operand is
  2121. floating point, @samp{/} converts the other operand to floating
  2122. point.
  2123.  
  2124. @example
  2125. 16.0 / 3   @result{} 5.333333333333333
  2126. 16   / 3.0 @result{} 5.333333333333333
  2127. 16.0 / 3.0 @result{} 5.333333333333333
  2128. 16   / 3   @result{} 5
  2129. @end example
  2130.  
  2131. The remainder operator @samp{%} is not allowed for floating-point
  2132. operands, because it is not needed.  The concept of remainder makes
  2133. sense for integers because the result of division of integers has to
  2134. be an integer.  For floating point, the result of division is a
  2135. floating-point number, in other words a fraction, which will differ
  2136. from the exact result only by a very small amount.
  2137.  
  2138. There are functions in the standard C library to calculate remainders
  2139. from integral-values division of floating-point numbers.
  2140. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  2141. Reference Manual}.
  2142.  
  2143. Integer division overflows in one specific case: dividing the smallest
  2144. negative value for the data type (@pxref{Maximum and Minimum Values})
  2145. by @minus{}1.  That's because the correct result, which is the
  2146. corresponding positive number, does not fit (@pxref{Integer Overflow})
  2147. in the same number of bits.  On some computers now in use, this always
  2148. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  2149. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  2150.  
  2151. Division by zero leads to unpredictable results---depending on the
  2152. type of computer, it might cause a signal @code{SIGFPE}, or it might
  2153. produce a numeric result.
  2154.  
  2155. @cindex division by zero
  2156. @cindex zero, division by
  2157. @strong{Watch out:} Make sure the program does not divide by zero.  If
  2158. you can't prove that the divisor is not zero, test whether it is zero,
  2159. and skip the division if so.
  2160.  
  2161. @node Numeric Comparisons
  2162. @section Numeric Comparisons
  2163. @cindex numeric comparisons
  2164. @cindex comparisons
  2165. @cindex operators, comparison
  2166. @cindex equal operator
  2167. @cindex not-equal operator
  2168. @cindex less-than operator
  2169. @cindex greater-than operator
  2170. @cindex less-or-equal operator
  2171. @cindex greater-or-equal operator
  2172. @cindex operator, equal
  2173. @cindex operator, not-equal
  2174. @cindex operator, less-than
  2175. @cindex operator, greater-than
  2176. @cindex operator, less-or-equal
  2177. @cindex operator, greater-or-equal
  2178. @cindex truth value
  2179.  
  2180. There are two kinds of comparison operators: @dfn{equality} and
  2181. @dfn{ordering}.  Equality comparisons test whether two expressions
  2182. have the same value.  The result is a @dfn{truth value}: a number that
  2183. is 1 for ``true'' and 0 for ``false.''
  2184.  
  2185. @example
  2186. a == b   /* @r{Test for equal.}  */
  2187. a != b   /* @r{Test for not equal.}  */
  2188. @end example
  2189.  
  2190. The equality comparison is written @code{==} because plain @code{=}
  2191. is the assignment operator.
  2192.  
  2193. Ordering comparisons test which operand is greater or less.  Their
  2194. results are truth values.  These are the ordering comparisons of C:
  2195.  
  2196. @example
  2197. a < b   /* @r{Test for less-than.}  */
  2198. a > b   /* @r{Test for greater-than.}  */
  2199. a <= b  /* @r{Test for less-than-or-equal.}  */
  2200. a >= b  /* @r{Test for greater-than-or-equal.}  */
  2201. @end example
  2202.  
  2203. For any integers @code{a} and @code{b}, exactly one of the comparisons
  2204. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  2205. mathematics.  However, if @code{a} and @code{b} are special floating
  2206. point values (not ordinary numbers), all three can be false.
  2207. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  2208.  
  2209. @node Shift Operations
  2210. @section Shift Operations
  2211. @cindex shift operators
  2212. @cindex operators, shift
  2213. @cindex operators, shift
  2214. @cindex shift count
  2215.  
  2216. @dfn{Shifting} an integer means moving the bit values to the left or
  2217. right within the bits of the data type.  Shifting is defined only for
  2218. integers.  Here's the way to write it:
  2219.  
  2220. @example
  2221. /* @r{Left shift.}  */
  2222. 5 << 2 @result{} 20
  2223.  
  2224. /* @r{Right shift.}  */
  2225. 5 >> 2 @result{} 1
  2226. @end example
  2227.  
  2228. @noindent
  2229. The left operand is the value to be shifted, and the right operand
  2230. says how many bits to shift it (the @dfn{shift count}).  The left
  2231. operand is promoted (@pxref{Operand Promotions}), so shifting never
  2232. operates on a narrow integer type; it's always either @code{int} or
  2233. wider.  The value of the shift operator has the same type as the
  2234. promoted left operand.
  2235.  
  2236. @menu
  2237. * Bits Shifted In::     How shifting makes new bits to shift in.
  2238. * Shift Caveats::       Caveats of shift operations.
  2239. * Shift Hacks::         Clever tricks with shift operations.
  2240. @end menu
  2241.  
  2242. @node Bits Shifted In
  2243. @subsection Shifting Makes New Bits
  2244.  
  2245. A shift operation shifts towards one end of the number and has to
  2246. generate new bits at the other end.
  2247.  
  2248. Shifting left one bit must generate a new least significant bit.  It
  2249. always brings in zero there.  It is equivalent to multiplying by the
  2250. appropriate power of 2.  For example,
  2251.  
  2252. @example
  2253. 5 << 3     @r{is equivalent to}   5 * 2*2*2
  2254. -10 << 4   @r{is equivalent to}   -10 * 2*2*2*2
  2255. @end example
  2256.  
  2257. The meaning of shifting right depends on whether the data type is
  2258. signed or unsigned (@pxref{Signed and Unsigned Types}).  For a signed
  2259. data type, it performs ``arithmetic shift,'' which keeps the number's
  2260. sign unchanged by duplicating the sign bit.  For an unsigned data
  2261. type, it performs ``logical shift,'' which always shifts in zeros at
  2262. the most significant bit.
  2263.  
  2264. In both cases, shifting right one bit is division by two, rounding
  2265. towards negative infinity.  For example,
  2266.  
  2267. @example
  2268. (unsigned) 19 >> 2 @result{} 4
  2269. (unsigned) 20 >> 2 @result{} 5
  2270. (unsigned) 21 >> 2 @result{} 5
  2271. @end example
  2272.  
  2273. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  2274. @code{a / 2}.  They both divide by 2, but @samp{/} rounds toward
  2275. zero.
  2276.  
  2277. The shift count must be zero or greater.  Shifting by a negative
  2278. number of bits gives machine-dependent results.
  2279.  
  2280. @node Shift Caveats
  2281. @subsection Caveats for Shift Operations
  2282.  
  2283. @strong{Warning:} If the shift count is greater than or equal to the
  2284. width in bits of the first operand, the results are machine-dependent.
  2285. Logically speaking, the ``correct'' value would be either -1 (for
  2286. right shift of a negative number) or 0 (in all other cases), but what
  2287. it really generates is whatever the machine's shift instruction does in
  2288. that case.  So unless you can prove that the second operand is not too
  2289. large, write code to check it at run time.
  2290.  
  2291. @strong{Warning:} Never rely on how the shift operators relate in
  2292. precedence to other arithmetic binary operators.  Programmers don't
  2293. remember these precedences, and won't understand the code.  Always use
  2294. parentheses to explicitly specify the nesting, like this:
  2295.  
  2296. @example
  2297. a + (b << 5)   /* @r{Shift first, then add.}  */
  2298. (a + b) << 5   /* @r{Add first, then shift.}  */
  2299. @end example
  2300.  
  2301. Note: according to the C standard, shifting of signed values isn't
  2302. guaranteed to work properly when the value shifted is negative, or
  2303. becomes negative during the operation of shifting left.  However, only
  2304. pedants have a reason to be concerned about this; only computers with
  2305. strange shift instructions could plausibly do this wrong.  In GNU C,
  2306. the operation always works as expected,
  2307.  
  2308. @node Shift Hacks
  2309. @subsection Shift Hacks
  2310.  
  2311. You can use the shift operators for various useful hacks.  For
  2312. example, given a date specified by day of the month @code{d}, month
  2313. @code{m}, and year @code{y}, you can store the entire date in a single
  2314. integer @code{date}:
  2315.  
  2316. @example
  2317. unsigned int d = 12;
  2318. unsigned int m = 6;
  2319. unsigned int y = 1983;
  2320. unsigned int date = ((y << 4) + m) << 5) + d;
  2321. @end example
  2322.  
  2323. @noindent
  2324. To extract the original day, month, and year out of
  2325. @code{date}, use a combination of shift and remainder.
  2326.  
  2327. @example
  2328. d = date % 32;
  2329. m = (date >> 5) % 16;
  2330. y = date >> 9;
  2331. @end example
  2332.  
  2333. @code{-1 << LOWBITS} is a clever way to make an integer whose
  2334. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  2335. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  2336. multiplication, since negating a value is equivalent to multiplying it
  2337. by @minus{}1.
  2338.  
  2339. @node Bitwise Operations
  2340. @section Bitwise Operations
  2341. @cindex bitwise operators
  2342. @cindex operators, bitwise
  2343. @cindex negation, bitwise
  2344. @cindex conjunction, bitwise
  2345. @cindex disjunction, bitwise
  2346.  
  2347. Bitwise operators operate on integers, treating each bit independently.
  2348. They are not allowed for floating-point types.
  2349.  
  2350. The examples in this section use binary constants, starting with
  2351. @samp{0b} (@pxref{Integer Constants}).  They stand for 32-bit integers
  2352. of type @code{int}.
  2353.  
  2354. @table @code
  2355. @item ~@code{a}
  2356. Unary operator for bitwise negation; this changes each bit of
  2357. @code{a} from 1 to 0 or from 0 to 1.
  2358.  
  2359. @example
  2360. ~0b10101000 @result{} 0b11111111111111111111111101010111
  2361. ~0 @result{} 0b11111111111111111111111111111111
  2362. ~0b11111111111111111111111111111111 @result{} 0
  2363. ~ (-1) @result{} 0
  2364. @end example
  2365.  
  2366. It is useful to remember that @code{~@var{x} + 1} equals
  2367. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  2368. @code{-@var{x} - 1}.  The last example above shows this with @minus{}1
  2369. as @var{x}.
  2370.  
  2371. @item @code{a} & @code{b}
  2372. Binary operator for bitwise ``and'' or ``conjunction.''  Each bit in
  2373. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  2374.  
  2375. @example
  2376. 0b10101010 & 0b11001100 @result{} 0b10001000
  2377. @end example
  2378.  
  2379. @item @code{a} | @code{b}
  2380. Binary operator for bitwise ``or'' (``inclusive or'' or
  2381. ``disjunction'').  Each bit in the result is 1 if that bit is 1 in
  2382. either @code{a} or @code{b}.
  2383.  
  2384. @example
  2385. 0b10101010 | 0b11001100 @result{} 0b11101110
  2386. @end example
  2387.  
  2388. @item @code{a} ^ @code{b}
  2389. Binary operator for bitwise ``xor'' (``exclusive or'').  Each bit in
  2390. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  2391.  
  2392. @example
  2393. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  2394. @end example
  2395. @end table
  2396.  
  2397. To understand the effect of these operators on signed integers, keep
  2398. in mind that all modern computers use two's-complement representation
  2399. (@pxref{Integer Representations}) for negative integers.  This means
  2400. that the highest bit of the number indicates the sign; it is 1 for a
  2401. negative number and 0 for a positive number.  In a negative number,
  2402. the value in the other bits @emph{increases} as the number gets closer
  2403. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  2404. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  2405.  
  2406. @strong{Warning:} C defines a precedence ordering for the bitwise
  2407. binary operators, but you should never rely on it.   You should
  2408. never rely on how bitwise binary operators relate in precedence to the
  2409. arithmetic and shift binary operators.  Other programmers don't
  2410. remember this precedence ordering, so always use parentheses to
  2411. explicitly specify the nesting.
  2412.  
  2413. For example, suppose @code{offset} is an integer that specifies
  2414. the offset within shared memory of a table, except that its bottom few
  2415. bits (@code{LOWBITS} says how many) are special flags.  Here's
  2416. how to get just that offset and add it to the base address.
  2417.  
  2418. @example
  2419. shared_mem_base + (offset & (-1 << LOWBITS))
  2420. @end example
  2421.  
  2422. Thanks to the outer set of parentheses, we don't need to know whether
  2423. @samp{&} has higher precedence than @samp{+}.  Thanks to the inner
  2424. set, we don't need to know whether @samp{&} has higher precedence than
  2425. @samp{<<}.  But we can rely on all unary operators to have higher
  2426. precedence than any binary operator, so we don't need parentheses
  2427. around the left operand of @samp{<<}.
  2428.  
  2429. @node Assignment Expressions
  2430. @chapter Assignment Expressions
  2431. @cindex assignment expressions
  2432. @cindex operators, assignment
  2433.  
  2434. As a general concept in programming, an @dfn{assignment} is a
  2435. construct that stores a new value into a place where values can be
  2436. stored---for instance, in a variable.  Such places are called
  2437. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  2438.  
  2439. An assignment in C is an expression because it has a value; we call
  2440. it an @dfn{assignment expression}.  A simple assignment looks like
  2441.  
  2442. @example
  2443. @var{lvalue} = @var{value-to-store}
  2444. @end example
  2445.  
  2446. @noindent
  2447. We say it assigns the value of the expression @var{value-to-store} to
  2448. the location @var{lvalue}, or that it stores @var{value-to-store}
  2449. there.  You can think of the ``l'' in ``lvalue'' as standing for
  2450. ``left,'' since that's what you put on the left side of the assignment
  2451. operator.
  2452.  
  2453. However, that's not the only way to use an lvalue, and not all lvalues
  2454. can be assigned to.  To use the lvalue in the left side of an
  2455. assignment, it has to be @dfn{modifiable}.  In C, that means it was
  2456. not declared with the type qualifier @code{const} (@pxref{const}).
  2457.  
  2458. The value of the assignment expression is that of @var{lvalue} after
  2459. the new value is stored in it.  This means you can use an assignment
  2460. inside other expressions.  Assignment operators are right-associative
  2461. so that
  2462.  
  2463. @example
  2464. x = y = z = 0;
  2465. @end example
  2466.  
  2467. @noindent
  2468. is equivalent to
  2469.  
  2470. @example
  2471. x = (y = (z = 0));
  2472. @end example
  2473.  
  2474. This is the only useful way for them to associate;
  2475. the other way,
  2476.  
  2477. @example
  2478. ((x = y) = z) = 0;
  2479. @end example
  2480.  
  2481. @noindent
  2482. would be invalid since an assignment expression such as @code{x = y}
  2483. is not valid as an lvalue.
  2484.  
  2485. @strong{Warning:} Write parentheses around an assignment if you nest
  2486. it inside another expression, unless that is a conditional expression,
  2487. or comma-separated series, or another assignment.
  2488.  
  2489. @menu
  2490. * Simple Assignment::            The basics of storing a value.
  2491. * Lvalues::                      Expressions into which a value can be stored.
  2492. * Modifying Assignment::         Shorthand for changing an lvalue's contents.
  2493. * Increment/Decrement::          Shorthand for incrementing and decrementing
  2494.                                   an lvalue's contents.
  2495. * Postincrement/Postdecrement::  Accessing then incrementing or decrementing.
  2496. * Assignment in Subexpressions:: How to avoid ambiguity.
  2497. * Write Assignments Separately:: Write assignments as separate statements.
  2498. @end menu
  2499.  
  2500. @node Simple Assignment
  2501. @section Simple Assignment
  2502. @cindex simple assignment
  2503. @cindex assignment, simple
  2504.  
  2505. A @dfn{simple assignment expression} computes the value of the right
  2506. operand and stores it into the lvalue on the left.  Here is a simple
  2507. assignment expression that stores 5 in @code{i}:
  2508.  
  2509. @example
  2510. i = 5
  2511. @end example
  2512.  
  2513. @noindent
  2514. We say that this is an @dfn{assignment to} the variable @code{i} and
  2515. that it @dfn{assigns} @code{i} the value 5.  It has no semicolon
  2516. because it is an expression (so it has a value).  Adding a semicolon
  2517. at the end would make it a statement (@pxref{Expression Statement}).
  2518.  
  2519. Here is another example of a simple assignment expression.  Its
  2520. operands are not simple, but the kind of assignment done here is
  2521. simple assignment.
  2522.  
  2523. @example
  2524. x[foo ()] = y + 6
  2525. @end example
  2526.  
  2527. A simple assignment with two different numeric data types converts the
  2528. right operand value to the lvalue's type, if possible.  It can convert
  2529. any numeric type to any other numeric type.
  2530.  
  2531. Simple assignment is also allowed on some non-numeric types: pointers
  2532. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2533. unions (@pxref{Unions}).
  2534.  
  2535. @strong{Warning:} Assignment is not allowed on arrays because
  2536. there are no array values in C; C variables can be arrays, but these
  2537. arrays cannot be manipulated as wholes.  @xref{Limitations of C
  2538. Arrays}.
  2539.  
  2540. @xref{Assignment Type Conversions}, for the complete rules about data
  2541. types used in assignments.
  2542.  
  2543. @node Lvalues
  2544. @section Lvalues
  2545. @cindex lvalues
  2546.  
  2547. An expression that identifies a memory space that holds a value is
  2548. called an @dfn{lvalue}, because it is a location that can hold a value.
  2549.  
  2550. The standard kinds of lvalues are:
  2551.  
  2552. @itemize @bullet
  2553. @item
  2554. A variable.
  2555.  
  2556. @item
  2557. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2558. unary @samp{*}.
  2559.  
  2560. @item
  2561. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2562. the structure value is an lvalue.
  2563.  
  2564. @item
  2565. A structure field reference using @samp{->}.  This is always an lvalue
  2566. since @samp{->} implies pointer dereference.
  2567.  
  2568. @item
  2569. A union alternative reference (@pxref{Unions}), on the same conditions
  2570. as for structure fields.
  2571.  
  2572. @item
  2573. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2574. is an lvalue.
  2575. @end itemize
  2576.  
  2577. If an expression's outermost operation is any other operator, that
  2578. expression is not an lvalue.  Thus, the variable @code{x} is an
  2579. lvalue, but @code{x + 0} is not, even though these two expressions
  2580. compute the same value (assuming @code{x} is a number).
  2581.  
  2582. An array can be an lvalue (the rules above determine whether it is
  2583. one), but using the array in an expression converts it automatically
  2584. to a pointer to the first element.  The result of this conversion is
  2585. not an lvalue.  Thus, if the variable @code{a} is an array, you can't
  2586. use @code{a} by itself as the left operand of an assignment.  But you
  2587. can assign to an element of @code{a}, such as @code{a[0]}.  That is an
  2588. lvalue since @code{a} is an lvalue.
  2589.  
  2590. @node Modifying Assignment
  2591. @section Modifying Assignment
  2592. @cindex modifying assignment
  2593. @cindex assignment, modifying
  2594.  
  2595. You can abbreviate the common construct
  2596.  
  2597. @example
  2598. @var{lvalue} = @var{lvalue} + @var{expression}
  2599. @end example
  2600.  
  2601. @noindent
  2602. as
  2603.  
  2604. @example
  2605. @var{lvalue} += @var{expression}
  2606. @end example
  2607.  
  2608. This is known as a @dfn{modifying assignment}.  For instance,
  2609.  
  2610. @example
  2611. i = i + 5;
  2612. i += 5;
  2613. @end example
  2614.  
  2615. @noindent
  2616. shows two statements that are equivalent.  The first uses
  2617. simple assignment; the second uses modifying assignment.
  2618.  
  2619. Modifying assignment works with any binary arithmetic operator.  For
  2620. instance, you can subtract something from an lvalue like this,
  2621.  
  2622. @example
  2623. @var{lvalue} -= @var{expression}
  2624. @end example
  2625.  
  2626. @noindent
  2627. or multiply it by a certain amount like this,
  2628.  
  2629. @example
  2630. @var{lvalue} *= @var{expression}
  2631. @end example
  2632.  
  2633. @noindent
  2634. or shift it by a certain amount like this.
  2635.  
  2636. @example
  2637. @var{lvalue} <<= @var{expression}
  2638. @var{lvalue} >>= @var{expression}
  2639. @end example
  2640.  
  2641. In most cases, this feature adds no power to the language, but it
  2642. provides substantial convenience.  Also, when @var{lvalue} contains
  2643. code that has side effects, the simple assignment performs those side
  2644. effects twice, while the modifying assignment performs them once.  For
  2645. instance,
  2646.  
  2647. @example
  2648. x[foo ()] = x[foo ()] + 5;
  2649. @end example
  2650.  
  2651. @noindent
  2652. calls @code{foo} twice, and it could return different values each
  2653. time.  If @code{foo ()} returns 1 the first time and 3 the second
  2654. time, then the effect could be to add @code{x[3]} and 5 and store the
  2655. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2656. result in @code{x[3]}.  We don't know which of the two it will do,
  2657. because C does not specify which call to @code{foo} is computed first.
  2658.  
  2659. Such a statement is not well defined, and shouldn't be used.
  2660.  
  2661. By contrast,
  2662.  
  2663. @example
  2664. x[foo ()] += 5;
  2665. @end example
  2666.  
  2667. @noindent
  2668. is well defined: it calls @code{foo} only once to determine which
  2669. element of @code{x} to adjust, and it adjusts that element by adding 5
  2670. to it.
  2671.  
  2672. @node Increment/Decrement
  2673. @section Increment and Decrement Operators
  2674. @cindex increment operator
  2675. @cindex decrement operator
  2676. @cindex operator, increment
  2677. @cindex operator, decrement
  2678. @cindex preincrement expression
  2679. @cindex predecrement expression
  2680.  
  2681. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2682. @dfn{decrement} operators.  When used on a numeric value, they add or
  2683. subtract 1.  We don't consider them assignments, but they are
  2684. equivalent to assignments.
  2685.  
  2686. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2687. @dfn{preincrement} or @dfn{predecrement}.  This adds or subtracts 1
  2688. and the result becomes the expression's value.  For instance,
  2689.  
  2690. @example
  2691. #include <stdio.h>   /* @r{Declares @code{printf}.} */
  2692.  
  2693. int
  2694. main (void)
  2695. @{
  2696.   int i = 5;
  2697.   printf ("%d\n", i);
  2698.   printf ("%d\n", ++i);
  2699.   printf ("%d\n", i);
  2700.   return 0;
  2701. @}
  2702. @end example
  2703.  
  2704. @noindent
  2705. prints lines containing 5, 6, and 6 again.  The expression @code{++i}
  2706. increments @code{i} from 5 to 6, and has the value 6, so the output
  2707. from @code{printf} on that line says @samp{6}.
  2708.  
  2709. Using @samp{--} instead, for predecrement,
  2710.  
  2711. @example
  2712. #include <stdio.h>   /* @r{Declares @code{printf}.} */
  2713.  
  2714. int
  2715. main (void)
  2716. @{
  2717.   int i = 5;
  2718.   printf ("%d\n", i);
  2719.   printf ("%d\n", --i);
  2720.   printf ("%d\n", i);
  2721.   return 0;
  2722. @}
  2723. @end example
  2724.  
  2725. @noindent
  2726. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2727. again @samp{4}.
  2728.  
  2729. @node Postincrement/Postdecrement
  2730. @section Postincrement and Postdecrement
  2731. @cindex postincrement expression
  2732. @cindex postdecrement expression
  2733. @cindex operator, postincrement
  2734. @cindex operator, postdecrement
  2735.  
  2736. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2737. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2738. increments or decrement it.  Thus, the value of @code{i++} is the same
  2739. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2740. little later.''  This is called @dfn{postincrement} or
  2741. @dfn{postdecrement}.
  2742.  
  2743. For example,
  2744.  
  2745. @example
  2746. #include <stdio.h>   /* @r{Declares @code{printf}.} */
  2747.  
  2748. int
  2749. main (void)
  2750. @{
  2751.   int i = 5;
  2752.   printf ("%d\n", i);
  2753.   printf ("%d\n", i++);
  2754.   printf ("%d\n", i);
  2755.   return 0;
  2756. @}
  2757. @end example
  2758.  
  2759. @noindent
  2760. prints lines containing 5, again 5, and 6.  The expression @code{i++}
  2761. has the value 5, which is the value of @code{i} at the time,
  2762. but it increments @code{i} from 5 to 6 just a little later.
  2763.  
  2764. How much later is ``just a little later''?  That is flexible.  The
  2765. increment has to happen by the next @dfn{sequence point}.  In simple cases,
  2766. that means by the end of the statement.  @xref{Sequence Points}.
  2767.  
  2768. If a unary operator precedes a postincrement or postincrement expression,
  2769. the increment nests inside:
  2770.  
  2771. @example
  2772. -a++   @r{is equivalent to}   -(a++)
  2773. @end example
  2774.  
  2775. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2776. it can't be incremented.
  2777.  
  2778. @node Assignment in Subexpressions
  2779. @section Pitfall: Assignment in Subexpressions
  2780. @cindex assignment in subexpressions
  2781. @cindex subexpressions, assignment in
  2782.  
  2783. In C, the order of computing parts of an expression is not fixed.
  2784. Aside from a few special cases, the operations can be computed in any
  2785. order.  If one part of the expression has an assignment to @code{x}
  2786. and another part of the expression uses @code{x}, the result is
  2787. unpredictable because that use might be computed before or after the
  2788. assignment.
  2789.  
  2790. Here's an example of ambiguous code:
  2791.  
  2792. @example
  2793. x = 20;
  2794. printf ("%d %d\n", x, x = 4);
  2795. @end example
  2796.  
  2797. @noindent
  2798. If the second argument, @code{x}, is computed before the third argument,
  2799. @code{x = 4}, the second argument's value will be 20.  If they are
  2800. computed in the other order, the second argument's value will be 4.
  2801.  
  2802. Here's one way to make that code unambiguous:
  2803.  
  2804. @example
  2805. y = 20;
  2806. printf ("%d %d\n", y, x = 4);
  2807. @end example
  2808.  
  2809. Here's another way, with the other meaning:
  2810.  
  2811. @example
  2812. x = 4;
  2813. printf ("%d %d\n", x, x);
  2814. @end example
  2815.  
  2816. This issue applies to all kinds of assignments, and to the increment
  2817. and decrement operators, which are equivalent to assignments.
  2818. @xref{Order of Execution}, for more information about this.
  2819.  
  2820. However, it can be useful to write assignments inside an
  2821. @code{if}-condition or @code{while}-test along with logical operators.
  2822. @xref{Logicals and Assignments}.
  2823.  
  2824. @node Write Assignments Separately
  2825. @section Write Assignments in Separate Statements
  2826.  
  2827. It is often convenient to write an assignment inside an
  2828. @code{if}-condition, but that can reduce the readability of the
  2829. program.  Here's an example of what to avoid:
  2830.  
  2831. @example
  2832. if (x = advance (x))
  2833.  @r{@dots{}}
  2834. @end example
  2835.  
  2836. The idea here is to advance @code{x} and test if the value is nonzero.
  2837. However, readers might miss the fact that it uses @samp{=} and not
  2838. @samp{==}.  In fact, writing @samp{=} where @samp{==} was intended
  2839. inside a condition is a common error, so GNU C can give warnings when
  2840. @samp{=} appears in a way that suggests it's an error.
  2841.  
  2842. It is much clearer to write the assignment as a separate statement, like this:
  2843.  
  2844. @example
  2845. x = advance (x);
  2846. if (x != 0)
  2847.  @r{@dots{}}
  2848. @end example
  2849.  
  2850. @noindent
  2851. This makes it unmistakably clear that @code{x} is assigned a new value.
  2852.  
  2853. Another method is to use the comma operator (@pxref{Comma Operator}),
  2854. like this:
  2855.  
  2856. @example
  2857. if (x = advance (x), x != 0)
  2858.  @r{@dots{}}
  2859. @end example
  2860.  
  2861. @noindent
  2862. However, putting the assignment in a separate statement is usually clearer
  2863. unless the assignment is very short, because it reduces nesting.
  2864.  
  2865. @node Execution Control Expressions
  2866. @chapter Execution Control Expressions
  2867. @cindex execution control expressions
  2868. @cindex expressions, execution control
  2869.  
  2870. This chapter describes the C operators that combine expressions to
  2871. control which of those expressions execute, or in which order.
  2872.  
  2873. @menu
  2874. * Logical Operators::           Logical conjunction, disjunction, negation.
  2875. * Logicals and Comparison::     Logical operators with comparison operators.
  2876. * Logicals and Assignments::    Assignments with logical operators.
  2877. * Conditional Expression::      An if/else construct inside expressions.
  2878. * Comma Operator::              Build a sequence of subexpressions.
  2879. @end menu
  2880.  
  2881. @node Logical Operators
  2882. @section Logical Operators
  2883. @cindex logical operators
  2884. @cindex operators, logical
  2885. @cindex conjunction operator
  2886. @cindex disjunction operator
  2887. @cindex negation operator, logical
  2888.  
  2889. The @dfn{logical operators} combine truth values, which are normally
  2890. represented in C as numbers.  Any expression with a numeric value is a
  2891. valid truth value: zero means false, and any other value means true.
  2892. A pointer type is also meaningful as a truth value; a null pointer
  2893. (which is zero) means false, and a non-null pointer means true
  2894. (@pxref{Pointer Types}).  The value of a logical operator is always 1
  2895. or 0 and has type @code{int} (@pxref{Integer Types}).
  2896.  
  2897. The logical operators are used mainly in the condition of an @code{if}
  2898. statement, or in the end test in a @code{for} statement or
  2899. @code{while} statement (@pxref{Statements}).  However, they are valid
  2900. in any context where an integer-valued expression is allowed.
  2901.  
  2902. @table @samp
  2903. @item ! @var{exp}
  2904. Unary operator for logical ``not.''  The value is 1 (true) if
  2905. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2906.  
  2907. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2908. function call, you should write parentheses around it.
  2909.  
  2910. @item @var{left} && @var{right}
  2911. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2912. @var{right}.  If both of the operands are true, the @samp{&&} expression
  2913. gives the value 1 (which is true).  Otherwise, the @samp{&&} expression
  2914. gives the value 0 (false).  If @var{left} yields a false value,
  2915. that determines the overall result, so @var{right} is not computed.
  2916.  
  2917. @item @var{left} || @var{right}
  2918. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2919. @var{right}.  If at least one of the operands is true, the @samp{||} expression
  2920. gives the value 1 (which is true).  Otherwise, the @samp{||} expression
  2921. gives the value 0 (false).  If @var{left} yields a true value,
  2922. that determines the overall result, so @var{right} is not computed.
  2923. @end table
  2924.  
  2925. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2926. and @samp{||}.  When you use them together, always use parentheses to
  2927. specify explicitly how they nest, as shown here:
  2928.  
  2929. @example
  2930. if ((r != 0 && x % r == 0)
  2931.     ||
  2932.     (s != 0 && x % s == 0))
  2933. @end example
  2934.  
  2935. @node Logicals and Comparison
  2936. @section Logical Operators and Comparisons
  2937.  
  2938. The most common thing to use inside the logical operators is a
  2939. comparison.  Conveniently, @samp{&&} and @samp{||} have lower
  2940. precedence than comparison operators and arithmetic operators, so we
  2941. can write expressions like this without parentheses and get the
  2942. nesting that is natural: two comparison operations that must both be
  2943. true.
  2944.  
  2945. @example
  2946. if (r != 0 && x % r == 0)
  2947. @end example
  2948.  
  2949. @noindent
  2950. This example also shows how it is useful that @samp{&&} guarantees to
  2951. skip the right operand if the left one turns out false.  Because of
  2952. that, this code never tries to divide by zero.
  2953.  
  2954. This is equivalent:
  2955.  
  2956. @example
  2957. if (r && x % r == 0)
  2958. @end example
  2959.  
  2960. @noindent
  2961. A truth value is simply a number, so @code{r}
  2962. as a truth value tests whether it is nonzero.
  2963. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2964. So it is better style to write the explicit @code{!= 0}.
  2965.  
  2966. Here's another equivalent way to write it:
  2967.  
  2968. @example
  2969. if (!(r == 0) && x % r == 0)
  2970. @end example
  2971.  
  2972. @noindent
  2973. This illustrates the unary @samp{!} operator, and the need to
  2974. write parentheses around its operand.
  2975.  
  2976. @node Logicals and Assignments
  2977. @section Logical Operators and Assignments
  2978.  
  2979. There are cases where assignments nested inside the condition can
  2980. actually make a program @emph{easier} to read.  Here is an example
  2981. using a hypothetical type @code{list} which represents a list; it
  2982. tests whether the list has at least two links, using hypothetical
  2983. functions, @code{nonempty} which is true of the argument is a nonempty
  2984. list, and @code{list_next} which advances from one list link to the
  2985. next.  We assume that a list is never a null pointer, so that the
  2986. assignment expressions are always ``true.''
  2987.  
  2988. @example
  2989. if (nonempty (list)
  2990.    && (temp1 = list_next (list))
  2991.    && nonempty (temp1)
  2992.    && (temp2 = list_next (temp1)))
  2993.  @r{@dots{}}  /* @r{use @code{temp1} and @code{temp2}} */
  2994. @end example
  2995.  
  2996. @noindent
  2997. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2998. the rest of the code if a call to @code{nonempty} says ``false.''  The
  2999. only natural place to put the assignments is among those calls.
  3000.  
  3001. It would be possible to rewrite this as several statements, but that
  3002. could make it much more cumbersome.  On the other hand, when the test
  3003. is even more complex than this one, splitting it into multiple
  3004. statements might be necessary for clarity.
  3005.  
  3006. If an empty list is a null pointer, we can dispense with calling
  3007. @code{nonempty}:
  3008.  
  3009. @example
  3010. if ((temp1 = list_next (list))
  3011.    && (temp2 = list_next (temp1)))
  3012. @r{@dots{}}
  3013. @end example
  3014.  
  3015. @node Conditional Expression
  3016. @section Conditional Expression
  3017. @cindex conditional expression
  3018. @cindex expression, conditional
  3019.  
  3020. C has a conditional expression that selects one of two expressions
  3021. to compute and get the value from.  It looks like this:
  3022.  
  3023. @example
  3024. @var{condition} ? @var{iftrue} : @var{iffalse}
  3025. @end example
  3026.  
  3027. @menu
  3028. * Conditional Rules::           Rules for the conditional operator.
  3029. * Conditional Branches::        About the two branches in a conditional.
  3030. @end menu
  3031.  
  3032. @node Conditional Rules
  3033. @subsection Rules for Conditional Operator
  3034.  
  3035. The first operand, @var{condition}, should be a value that can be
  3036. compared with zero---a number or a pointer.  If it is true (nonzero),
  3037. then the conditional expression computes @var{iftrue} and its value
  3038. becomes the value of the conditional expression.  Otherwise the
  3039. conditional expression computes @var{iffalse} and its value becomes
  3040. the value of the conditional expression.  The conditional expression
  3041. always computes just one of @var{iftrue} and @var{iffalse}, never both
  3042. of them.
  3043.  
  3044. Here's an example: the absolute value of a number @code{x}
  3045. can be written as @code{(x >= 0 ? x : -x)}.
  3046.  
  3047. @strong{Warning:} The conditional expression operators have rather low
  3048. syntactic precedence.  Except when the conditional expression is used
  3049. as an argument in a function call, write parentheses around it.  For
  3050. clarity, always write parentheses around it if it extends across more
  3051. than one line.
  3052.  
  3053. Assignment operators and the comma operator (@pxref{Comma Operator})
  3054. have lower precedence than conditional expression operators, so write
  3055. parentheses around those when they appear inside a conditional
  3056. expression.  @xref{Order of Execution}.
  3057.  
  3058. @node Conditional Branches
  3059. @subsection Conditional Operator Branches
  3060. @cindex branches of conditional expression
  3061.  
  3062. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  3063. conditional.
  3064.  
  3065. The two branches should normally have the same type, but a few
  3066. exceptions are allowed.  If they are both numeric types, the
  3067. conditional converts both to their common type (@pxref{Common Type}).
  3068.  
  3069. With pointers (@pxref{Pointers}), the two values can be pointers to
  3070. nearly compatible types (@pxref{Compatible Types}).  In this case, the
  3071. result type is a similar pointer whose target type combines all the
  3072. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  3073.  
  3074. If one branch has type @code{void *} and the other is a pointer to an
  3075. object (not to a function), the conditional converts the @code{void *}
  3076. branch to the type of the other.
  3077.  
  3078. If one branch is an integer constant with value zero and the other is
  3079. a pointer, the conditional converts zero to the pointer's type.
  3080.  
  3081. In GNU C, you can omit @var{iftrue} in a conditional expression.  In
  3082. that case, if @var{condition} is nonzero, its value becomes the value of
  3083. the conditional expression, after conversion to the common type.
  3084. Thus,
  3085.  
  3086. @example
  3087. x ? : y
  3088. @end example
  3089.  
  3090. @noindent
  3091. has the value of @code{x} if that is nonzero; otherwise, the value of
  3092. @code{y}.
  3093.  
  3094. @cindex side effect in ?:
  3095. @cindex ?: side effect
  3096. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  3097. In that case, writing that expression twice would carry out the side
  3098. effects twice, but writing it once does them just once.  For example,
  3099. if we suppose that the function @code{next_element} advances a pointer
  3100. variable to point to the next element in a list and returns the new
  3101. pointer,
  3102.  
  3103. @example
  3104. next_element () ? : default_pointer
  3105. @end example
  3106.  
  3107. @noindent
  3108. is a way to advance the pointer and use its new value if it isn't
  3109. null, but use @code{default_pointer} if that is null.  We must not do
  3110. it this way,
  3111.  
  3112. @example
  3113. next_element () ? next_element () : default_pointer
  3114. @end example
  3115.  
  3116. @noindent
  3117. because it would advance the pointer a second time.
  3118.  
  3119. @node Comma Operator
  3120. @section Comma Operator
  3121. @cindex comma operator
  3122. @cindex operator, comma
  3123.  
  3124. The comma operator stands for sequential execution of expressions.
  3125. The value of the comma expression comes from the last expression in
  3126. the sequence; the previous expressions are computed only for their
  3127. side effects.  It looks like this:
  3128.  
  3129. @example
  3130. @var{exp1}, @var{exp2} @r{@dots{}}
  3131. @end example
  3132.  
  3133. @noindent
  3134. You can bundle any number of expressions together this way, by putting
  3135. commas between them.
  3136.  
  3137. @menu
  3138. * Uses of Comma::       When to use the comma operator.
  3139. * Clean Comma::         Clean use of the comma operator.
  3140. * Avoid Comma::         When to not use the comma operator.
  3141. @end menu
  3142.  
  3143. @node Uses of Comma
  3144. @subsection The Uses of the Comma Operator
  3145.  
  3146. With commas, you can put several expressions into a place that
  3147. requires just one expression---for example, in the header of a
  3148. @code{for} statement.  This statement
  3149.  
  3150. @example
  3151. for (i = 0, j = 10, k = 20; i < n; i++)
  3152. @end example
  3153.  
  3154. @noindent
  3155. contains three assignment expressions, to initialize @code{i}, @code{j}
  3156. and @code{k}.  The syntax of @code{for} requires just one expression
  3157. for initialization; to include three assignments, we use commas to
  3158. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  3159. 20}.  This technique is also useful in the loop-advance expression,
  3160. the last of the three inside the @code{for} parentheses.
  3161.  
  3162. In the @code{for} statement and the @code{while} statement
  3163. (@pxref{Loop Statements}), a comma provides a way to perform some side
  3164. effect before the loop-exit test.  For example,
  3165.  
  3166. @example
  3167. while (printf ("At the test, x = %d\n", x), x != 0)
  3168. @end example
  3169.  
  3170. @node Clean Comma
  3171. @subsection Clean Use of the Comma Operator
  3172.  
  3173. Always write parentheses around a series of comma operators, except
  3174. when it is at top level in an expression statement, or within the
  3175. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  3176. statement (@pxref{Statements}).  For instance, in
  3177.  
  3178. @example
  3179. for (i = 0, j = 10, k = 20; i < n; i++)
  3180. @end example
  3181.  
  3182. @noindent
  3183. the commas between the assignments are clear because they are between
  3184. a parenthesis and a semicolon.
  3185.  
  3186. The arguments in a function call are also separated by commas, but that is
  3187. not an instance of the comma operator.  Note the difference between
  3188.  
  3189. @example
  3190. foo (4, 5, 6)
  3191. @end example
  3192.  
  3193. @noindent
  3194. which passes three arguments to @code{foo} and
  3195.  
  3196. @example
  3197. foo ((4, 5, 6))
  3198. @end example
  3199.  
  3200. @noindent
  3201. which uses the comma operator and passes just one argument
  3202. (with value 6).
  3203.  
  3204. @strong{Warning:} don't use the comma operator around an argument
  3205. of a function unless it helps understand the code.  When you do so,
  3206. don't put part of another argument on the same line.  Instead, add a
  3207. line break to make the parentheses around the comma operator easier to
  3208. see, like this.
  3209.  
  3210. @example
  3211. foo ((mumble (x, y), frob (z)),
  3212.     *p)
  3213. @end example
  3214.  
  3215. @node Avoid Comma
  3216. @subsection When Not to Use the Comma Operator
  3217.  
  3218. You can use a comma in any subexpression, but in most cases it only
  3219. makes the code confusing, and it is clearer to raise all but the last
  3220. of the comma-separated expressions to a higher level.  Thus, instead
  3221. of this:
  3222.  
  3223. @example
  3224. x = (y += 4, 8);
  3225. @end example
  3226.  
  3227. @noindent
  3228. it is much clearer to write this:
  3229.  
  3230. @example
  3231. y += 4, x = 8;
  3232. @end example
  3233.  
  3234. @noindent
  3235. or this:
  3236.  
  3237. @example
  3238. y += 4;
  3239. x = 8;
  3240. @end example
  3241.  
  3242. Use commas only in the cases where there is no clearer alternative
  3243. involving multiple statements.
  3244.  
  3245. By contrast, don't hesitate to use commas in the expansion in a macro
  3246. definition.  The trade-offs of code clarity are different in that
  3247. case, because the @emph{use} of the macro may improve overall clarity
  3248. so much that the ugliness of the macro's @emph{definition} is a small
  3249. price to pay.  @xref{Macros}.
  3250.  
  3251. @node Binary Operator Grammar
  3252. @chapter Binary Operator Grammar
  3253. @cindex binary operator grammar
  3254. @cindex grammar, binary operator
  3255. @cindex operator precedence
  3256. @cindex precedence, operator
  3257. @cindex left-associative
  3258.  
  3259. @dfn{Binary operators} are those that take two operands, one
  3260. on the left and one on the right.
  3261.  
  3262. All the binary operators in C are syntactically left-associative.
  3263. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  3264. @var{op} b) @var{op} c}}.  However, you should only write repeated
  3265. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  3266. @samp{/}, because those cases are clear from algebra.  So it is ok to
  3267. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  3268. c} or @code{a % b % c}.
  3269.  
  3270. Each C operator has a @dfn{precedence}, which is its rank in the
  3271. grammatical order of the various operators.  The operators with the
  3272. highest precedence grab adjoining operands first; these expressions
  3273. then become operands for operators of lower precedence.
  3274.  
  3275. The precedence order of operators in C is fully specified, so any
  3276. combination of operations leads to a well-defined nesting.  We state
  3277. only part of the full precedence ordering here because it is bad
  3278. practice for C code to depend on the other cases.  For cases not
  3279. specified in this chapter, always use parentheses to make the nesting
  3280. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  3281. remembering anything about the C precedence order beyond what's stated
  3282. here.  I studied the full precedence table to write the parser, and
  3283. promptly forgot it again.  If you need to look up the full precedence order
  3284. to understand some C code, fix the code with parentheses so nobody else
  3285. needs to do that.}
  3286.  
  3287. You can depend on this subsequence of the precedence ordering
  3288. (stated from highest precedence to lowest):
  3289.  
  3290. @enumerate
  3291. @item
  3292. Component access (@samp{.} and @samp{->}).
  3293.  
  3294. @item
  3295. Unary prefix operators.
  3296.  
  3297. @item
  3298. Unary postfix operators.
  3299.  
  3300. @item
  3301. Multiplication, division, and remainder (they have the same precedence).
  3302.  
  3303. @item
  3304. Addition and subtraction (they have the same precedence).
  3305.  
  3306. @item
  3307. Comparisons---but watch out!
  3308.  
  3309. @item
  3310. Logical operators @samp{&&} and @samp{||}---but watch out!
  3311.  
  3312. @item
  3313. Conditional expression with @samp{?} and @samp{:}.
  3314.  
  3315. @item
  3316. Assignments.
  3317.  
  3318. @item
  3319. Sequential execution (the comma operator, @samp{,}).
  3320. @end enumerate
  3321.  
  3322. Two of the lines in the above list say ``but watch out!''  That means
  3323. that the line covers operators with subtly different precedence.
  3324. Never depend on the grammar of C to decide how two comparisons nest;
  3325. instead, always use parentheses to specify their nesting.
  3326.  
  3327. You can let several @samp{&&} operators associate, or several
  3328. @samp{||} operators, but always use parentheses to show how @samp{&&}
  3329. and @samp{||} nest with each other.  @xref{Logical Operators}.
  3330.  
  3331. There is one other precedence ordering that code can depend on:
  3332.  
  3333. @enumerate
  3334. @item
  3335. Unary postfix operators.
  3336.  
  3337. @item
  3338. Bitwise and shift operators---but watch out!
  3339.  
  3340. @item
  3341. Conditional expression with @samp{?} and @samp{:}.
  3342. @end enumerate
  3343.  
  3344. The caveat for bitwise and shift operators is like that for logical
  3345. operators: you can let multiple uses of one bitwise operator
  3346. associate, but always use parentheses to control nesting of dissimilar
  3347. operators.
  3348.  
  3349. These lists do not specify any precedence ordering between the bitwise
  3350. and shift operators of the second list and the binary operators above
  3351. conditional expressions in the first list.  When they come together,
  3352. parenthesize them.  @xref{Bitwise Operations}.
  3353.  
  3354. @node Order of Execution
  3355. @chapter Order of Execution
  3356. @cindex order of execution
  3357.  
  3358. The order of execution of a C program is not always obvious, and not
  3359. necessarily predictable.  This chapter describes what you can count on.
  3360.  
  3361. @menu
  3362. * Reordering of Operands::       Operations in C are not necessarily computed
  3363.                                   in the order they are written.
  3364. * Associativity and Ordering::   Some associative operations are performed
  3365.                                   in a particular order; others are not.    
  3366. * Sequence Points::              Some guarantees about the order of operations.
  3367. * Postincrement and Ordering::   Ambiguous excution order with postincrement.
  3368. * Ordering of Operands::         Evaluation order of operands
  3369.                                   and function arguments.
  3370. * Optimization and Ordering::    Compiler optimizations can reorder operations
  3371.                                   only if it has no impact on program results.
  3372. @end menu
  3373.  
  3374. @node Reordering of Operands
  3375. @section Reordering of Operands
  3376. @cindex ordering of operands
  3377. @cindex reordering of operands
  3378. @cindex operand execution ordering
  3379.  
  3380. The C language does not necessarily carry out operations within an
  3381. expression in the order they appear in the code.  For instance, in
  3382. this expression,
  3383.  
  3384. @example
  3385. foo () + bar ()
  3386. @end example
  3387.  
  3388. @noindent
  3389. @code{foo} might be called first or @code{bar} might be called first.
  3390. If @code{foo} updates a datum and @code{bar} uses that datum, the
  3391. results can be unpredictable.
  3392.  
  3393. The unpredictable order of computation of subexpressions also makes a
  3394. difference when one of them contains an assignment.  We already saw
  3395. this example of bad code,
  3396.  
  3397. @example
  3398. x = 20;
  3399. printf ("%d %d\n", x, x = 4);
  3400. @end example
  3401.  
  3402. @noindent
  3403. in which the second argument, @code{x}, has a different value
  3404. depending on whether it is computed before or after the assignment in
  3405. the third argument.
  3406.  
  3407. @node Associativity and Ordering
  3408. @section Associativity and Ordering
  3409. @cindex associativity and ordering
  3410.  
  3411. An associative binary operator, such as @code{+}, when used repeatedly
  3412. can combine any number of operands.  The operands' values may be
  3413. computed in any order.
  3414.  
  3415. If the values are integers and overflow can be ignored, they may be
  3416. combined in any order.  Thus, given four functions that return
  3417. @code{unsigned int}, calling them and adding their results as here
  3418.  
  3419. @example
  3420. (foo () + bar ()) + (baz () + quux ())
  3421. @end example
  3422.  
  3423. @noindent
  3424. may add up the results in any order.
  3425.  
  3426. By contrast, arithmetic on signed integers, with overflow significant,
  3427. is not really associative (@pxref{Integer Overflow}).  Thus, the
  3428. additions must be done in the order specified, obeying parentheses and
  3429. left-association.  That means computing @code{(foo () + bar ())} and
  3430. @code{(baz () + quux ())} first (in either order), then adding the
  3431. two.
  3432.  
  3433. The same applies to arithmetic on floating-point values, since that
  3434. too is not really associative.  However, the GCC option
  3435. @option{-funsafe-math-optimizations} allows the compiler to change the
  3436. order of calculation when an associative operation (associative in
  3437. exact mathematics) combines several operands.  The option takes effect
  3438. when compiling a module (@pxref{Compilation}).  Changing the order
  3439. of association can enable the program to pipeline the floating point
  3440. operations.
  3441.  
  3442. In all these cases, the four function calls can be done in any order.
  3443. There is no right or wrong about that.
  3444.  
  3445. @node Sequence Points
  3446. @section Sequence Points
  3447. @cindex sequence points
  3448. @cindex full expression
  3449.  
  3450. There are some points in the code where C makes limited guarantees
  3451. about the order of operations.  These are called @dfn{sequence
  3452. points}.  Here is where they occur:
  3453.  
  3454. @itemize @bullet
  3455. @item
  3456. At the end of a @dfn{full expression}; that is to say, an expression
  3457. that is not part of a larger expression.  All side effects specified
  3458. by that expression are carried out before execution moves
  3459. on to subsequent code.
  3460.  
  3461. @item
  3462. At the end of the first operand of certain operators: @samp{,},
  3463. @samp{&&}, @samp{||}, and @samp{?:}.  All side effects specified by
  3464. that expression are carried out before any execution of the
  3465. next operand.
  3466.  
  3467. The commas that separate arguments in a function call are @emph{not}
  3468. comma operators, and they do not create sequence points.  The rule
  3469. for function arguments and the rule for operands are different
  3470. (@pxref{Ordering of Operands}).
  3471.  
  3472. @item
  3473. Just before calling a function.  All side effects specified by the
  3474. argument expressions are carried out before calling the function.
  3475.  
  3476. If the function to be called is not constant---that is, if it is
  3477. computed by an expression---all side effects in that expression are
  3478. carried out before calling the function.
  3479. @end itemize
  3480.  
  3481. The ordering imposed by a sequence point applies locally to a limited
  3482. range of code, as stated above in each case.  For instance, the
  3483. ordering imposed by the comma operator does not apply to code outside
  3484. that comma operator.  Thus, in this code,
  3485.  
  3486. @example
  3487. (x = 5, foo (x)) + x * x
  3488. @end example
  3489.  
  3490. @noindent
  3491. the sequence point of the comma operator orders @code{x = 5} before
  3492. @code{foo (x)}, but @code{x * x} could be computed before or after
  3493. them.
  3494.  
  3495. @node Postincrement and Ordering
  3496. @section Postincrement and Ordering
  3497. @cindex postincrement and ordering
  3498. @cindex ordering and postincrement
  3499.  
  3500. Ordering requirements are loose with the postincrement and
  3501. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  3502. specify side effects to happen ``a little later.''  They must happen
  3503. before the next sequence point, but that still leaves room for various
  3504. meanings.  In this expression,
  3505.  
  3506. @example
  3507. z = x++ - foo ()
  3508. @end example
  3509.  
  3510. @noindent
  3511. it's unpredictable whether @code{x} gets incremented before or after
  3512. calling the function @code{foo}.  If @code{foo} refers to @code{x},
  3513. it might see the old value or it might see the incremented value.
  3514.  
  3515. In this perverse expression,
  3516.  
  3517. @example
  3518. x = x++
  3519. @end example
  3520.  
  3521. @noindent
  3522. @code{x} will certainly be incremented but the incremented value may
  3523. not stick.  If the incrementation of @code{x} happens after the
  3524. assignment to @code{x}, the incremented value will remain in place.
  3525. But if the incrementation happens first, the assignment will overwrite
  3526. that with the not-yet-incremented value, so the expression as a whole
  3527. will leave @code{x} unchanged.
  3528.  
  3529. @node Ordering of Operands
  3530. @section Ordering of Operands
  3531. @cindex ordering of operands
  3532. @cindex operand ordering
  3533.  
  3534. Operands and arguments can be computed in any order, but there are limits to
  3535. this intermixing in GNU C:
  3536.  
  3537. @itemize @bullet
  3538. @item
  3539. The operands of a binary arithmetic operator can be computed in either
  3540. order, but they can't be intermixed: one of them has to come first,
  3541. followed by the other.  Any side effects in the operand that's computed
  3542. first are executed before the other operand is computed.
  3543.  
  3544. @item
  3545. That applies to assignment operators too, except that in simple assignment
  3546. the previous value of the left operand is unused.
  3547.  
  3548. @item
  3549. The arguments in a function call can be computed in any order, but
  3550. they can't be intermixed.  Thus, one argument is fully computed, then
  3551. another, and so on until they are all done.  Any side effects in one argument
  3552. are executed before computation of another argument begins.
  3553. @end itemize
  3554.  
  3555. These rules don't cover side effects caused by postincrement and
  3556. postdecrement operators---those can be deferred up to the next
  3557. sequence point.
  3558.  
  3559. If you want to get pedantic, the fact is that GCC can reorder the
  3560. computations in many other ways provided that doesn't alter the result
  3561. of running the program.  However, because they don't alter the result
  3562. of running the program, they are negligible, unless you are concerned
  3563. with the values in certain variables at various times as seen by other
  3564. processes.  In those cases, you can use @code{volatile} to prevent
  3565. optimizations that would make them behave strangely.  @xref{volatile}.
  3566.  
  3567. @node Optimization and Ordering
  3568. @section Optimization and Ordering
  3569. @cindex optimization and ordering
  3570. @cindex ordering and optimization
  3571.  
  3572. Sequence points limit the compiler's freedom to reorder operations
  3573. arbitrarily, but optimizations can still reorder them if the compiler
  3574. concludes that this won't alter the results.  Thus, in this code,
  3575.  
  3576. @example
  3577. x++;
  3578. y = z;
  3579. x++;
  3580. @end example
  3581.  
  3582. @noindent
  3583. there is a sequence point after each statement, so the code is
  3584. supposed to increment @code{x} once before the assignment to @code{y}
  3585. and once after.  However, incrementing @code{x} has no effect on
  3586. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  3587. the code could be optimized into this:
  3588.  
  3589. @example
  3590. y = z;
  3591. x += 2;
  3592. @end example
  3593.  
  3594. Normally that has no effect except to make the program faster.  But
  3595. there are special situations where it can cause trouble due to things
  3596. that the compiler cannot know about, such as shared memory.  To limit
  3597. optimization in those places, use the @code{volatile} type qualifier
  3598. (@pxref{volatile}).
  3599.  
  3600. @node Primitive Types
  3601. @chapter Primitive Data Types
  3602. @cindex primitive types
  3603. @cindex types, primitive
  3604.  
  3605. This chapter describes all the primitive data types of C---that is,
  3606. all the data types that aren't built up from other types.  They
  3607. include the types @code{int} and @code{double} that we've already covered.
  3608.  
  3609. @menu
  3610. * Integer Types::                Description of integer types.
  3611. * Floating-Point Data Types::    Description of floating-point types.
  3612. * Complex Data Types::           Description of complex number types.
  3613. * The Void Type::                A type indicating no value at all.
  3614. * Other Data Types::             A brief summary of other types.
  3615. * Type Designators::             Referring to a data type abstractly.
  3616. @end menu
  3617.  
  3618. These types are all made up of bytes (@pxref{Storage}).
  3619.  
  3620. @node Integer Types
  3621. @section Integer Data Types
  3622. @cindex integer types
  3623. @cindex types, integer
  3624.  
  3625. Here we describe all the integer types and their basic
  3626. characteristics.  @xref{Integers in Depth}, for more information about
  3627. the bit-level integer data representations and arithmetic.
  3628.  
  3629. @menu
  3630. * Basic Integers::              Overview of the various kinds of integers.
  3631. * Signed and Unsigned Types::   Integers can either hold both negative and
  3632.                                  non-negative values, or only non-negative.
  3633. * Narrow Integers::             When to use smaller integer types.
  3634. * Integer Conversion::          Casting a value from one integer type
  3635.                                  to another.
  3636. * Boolean Type::                An integer type for boolean values.
  3637. * Integer Variations::          Sizes of integer types can vary
  3638.                                  across platforms.
  3639. @end menu
  3640.  
  3641. @node Basic Integers
  3642. @subsection Basic Integers
  3643.  
  3644. @findex char
  3645. @findex int
  3646. @findex short int
  3647. @findex long int
  3648. @findex long long int
  3649.  
  3650. Integer data types in C can be signed or unsigned.  An unsigned type
  3651. can represent only positive numbers and zero.  A signed type can
  3652. represent both positive and negative numbers, in a range spread almost
  3653. equally on both sides of zero.
  3654.  
  3655. Aside from signedness, the integer data types vary in size: how many
  3656. bytes long they are.  The size determines how many different integer
  3657. values the type can hold.
  3658.  
  3659. Here's a list of the signed integer data types, with the sizes they
  3660. have on most computers.  Each has a corresponding unsigned type; see
  3661. @ref{Signed and Unsigned Types}.
  3662.  
  3663. @table @code
  3664. @item signed char
  3665. One byte (8 bits).  This integer type is used mainly for integers that
  3666. represent characters, as part of arrays or other data structures.
  3667.  
  3668. @item short
  3669. @itemx short int
  3670. Two bytes (16 bits).
  3671.  
  3672. @item int
  3673. Four bytes (32 bits).
  3674.  
  3675. @item long
  3676. @itemx long int
  3677. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  3678. platform.  Typically it is 32 bits on 32-bit computers
  3679. and 64 bits on 64-bit computers, but there are exceptions.
  3680.  
  3681. @item long long
  3682. @itemx long long int
  3683. Eight bytes (64 bits).  Supported in GNU C in the 1980s, and
  3684. incorporated into standard C as of ISO C99.
  3685. @end table
  3686.  
  3687. You can omit @code{int} when you use @code{long} or @code{short}.
  3688. This is harmless and customary.
  3689.  
  3690. @node Signed and Unsigned Types
  3691. @subsection Signed and Unsigned Types
  3692. @cindex signed types
  3693. @cindex unsigned types
  3694. @cindex types, signed
  3695. @cindex types, unsigned
  3696. @findex signed
  3697. @findex unsigned
  3698.  
  3699. An unsigned integer type can represent only positive numbers and zero.
  3700. A signed type can represent both positive and negative number, in a
  3701. range spread almost equally on both sides of zero.  For instance,
  3702. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  3703. while @code{signed char} holds numbers from @minus{}128 to 127.  Each of
  3704. these types holds 256 different possible values, since they are both 8
  3705. bits wide.
  3706.  
  3707. Write @code{signed} or @code{unsigned} before the type keyword to
  3708. specify a signed or an unsigned type.  However, the integer types
  3709. other than @code{char} are signed by default; with them, @code{signed}
  3710. is a no-op.
  3711.  
  3712. Plain @code{char} may be signed or unsigned; this depends on the
  3713. compiler, the machine in use, and its operating system.
  3714.  
  3715. In many programs, it makes no difference whether @code{char} is
  3716. signed.  When it does matter, don't leave it to chance; write
  3717. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  3718. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  3719. Arctic Char.  When my meal arrived, I noted that the chef had not
  3720. signed it.  So I complained, ``This char is unsigned---I wanted a
  3721. signed char!''  Or rather, I would have said this if I had thought of
  3722. it fast enough.}
  3723.  
  3724. @node Narrow Integers
  3725. @subsection Narrow Integers
  3726.  
  3727. The types that are narrower than @code{int} are rarely used for
  3728. ordinary variables---we declare them @code{int} instead.  This is
  3729. because C converts those narrower types to @code{int} for any
  3730. arithmetic.  There is literally no reason to declare a local variable
  3731. @code{char}, for instance.
  3732.  
  3733. In particular, if the value is really a character, you should declare
  3734. the variable @code{int}.  Not @code{char}!  Using that narrow type can
  3735. force the compiler to truncate values for conversion, which is a
  3736. waste.  Furthermore, some functions return either a character value,
  3737. or @minus{}1 for ``no character.''  Using @code{int} keeps those
  3738. values distinct.
  3739.  
  3740. The narrow integer types are useful as parts of other objects, such as
  3741. arrays and structures.  Compare these array declarations, whose sizes
  3742. on 32-bit processors are shown:
  3743.  
  3744. @example
  3745. signed char ac[1000];   /* @r{1000 bytes} */
  3746. short as[1000];         /* @r{2000 bytes} */
  3747. int ai[1000];           /* @r{4000 bytes} */
  3748. long long all[1000];    /* @r{8000 bytes} */
  3749. @end example
  3750.  
  3751. In addition, character strings must be made up of @code{char}s,
  3752. because that's what all the standard library string functions expect.
  3753. Thus, array @code{ac} could be used as a character string, but the
  3754. others could not be.
  3755.  
  3756. @node Integer Conversion
  3757. @subsection Conversion among Integer Types
  3758.  
  3759. C converts between integer types implicitly in many situations.  It
  3760. converts the narrow integer types, @code{char} and @code{short}, to
  3761. @code{int} whenever they are used in arithmetic.  Assigning a new
  3762. value to an integer variable (or other lvalue) converts the value to
  3763. the variable's type.
  3764.  
  3765. You can also convert one integer type to another explicitly with a
  3766. @dfn{cast} operator.  @xref{Explicit Type Conversion}.
  3767.  
  3768. The process of conversion to a wider type is straightforward: the
  3769. value is unchanged.  The only exception is when converting a negative
  3770. value (in a signed type, obviously) to a wider unsigned type.  In that
  3771. case, the result is a positive value with the same bits
  3772. (@pxref{Integers in Depth}).
  3773.  
  3774. @cindex truncation
  3775. Converting to a narrower type, also called @dfn{truncation}, involves
  3776. discarding some of the value's bits.  This is not considered overflow
  3777. (@pxref{Integer Overflow}) because loss of significant bits is a
  3778. normal consequence of truncation.  Likewise for conversion between
  3779. signed and unsigned types of the same width.
  3780.  
  3781. More information about conversion for assignment is in
  3782. @ref{Assignment Type Conversions}.  For conversion for arithmetic,
  3783. see @ref{Argument Promotions}.
  3784.  
  3785. @node Boolean Type
  3786. @subsection Boolean Type
  3787. @cindex boolean type
  3788. @cindex type, boolean
  3789. @findex bool
  3790.  
  3791. The unsigned integer type @code{bool} holds truth values: its possible
  3792. values are 0 and 1.  Converting any nonzero value to @code{bool}
  3793. results in 1.  For example:
  3794.  
  3795. @example
  3796. bool a = 0;
  3797. bool b = 1;
  3798. bool c = 4; /* @r{Stores the value 1 in @code{c}.}  */
  3799. @end example
  3800.  
  3801. Unlike @code{int}, @code{bool} is not a keyword.  It is defined in
  3802. the header file @file{stdbool.h}.
  3803.  
  3804. @node Integer Variations
  3805. @subsection Integer Variations
  3806.  
  3807. The integer types of C have standard @emph{names}, but what they
  3808. @emph{mean} varies depending on the kind of platform in use:
  3809. which kind of computer, which operating system, and which compiler.
  3810. It may even depend on the compiler options used.
  3811.  
  3812. Plain @code{char} may be signed or unsigned; this depends on the
  3813. platform, too.  Even for GNU C, there is no general rule.
  3814.  
  3815. In theory, all of the integer types' sizes can vary.  @code{char} is
  3816. always considered one ``byte'' for C, but it is not necessarily an
  3817. 8-bit byte; on some platforms it may be more than 8 bits.  ISO C
  3818. specifies only that none of these types is narrower than the ones
  3819. above it in the list in @ref{Basic Integers}, and that @code{short}
  3820. has at least 16 bits.
  3821.  
  3822. It is possible that in the future GNU C will support platforms where
  3823. @code{int} is 64 bits long.  In practice, however, on today's real
  3824. computers, there is little variation; you can rely on the table
  3825. given previously (@pxref{Basic Integers}).
  3826.  
  3827. To be completely sure of the size of an integer type,
  3828. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3829. Their corresponding unsigned types add @samp{u} at the front.
  3830. To define these, include the header file @file{stdint.h}.
  3831.  
  3832. The GNU C Compiler compiles for some embedded controllers that use two
  3833. bytes for @code{int}.  On some, @code{int} is just one ``byte,'' and
  3834. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3835. 32 bits.  These processors can't support an ordinary operating system
  3836. (they may have their own specialized operating systems), and most C
  3837. programs do not try to support them.
  3838.  
  3839. @node Floating-Point Data Types
  3840. @section Floating-Point Data Types
  3841. @cindex floating-point types
  3842. @cindex types, floating-point
  3843. @findex double
  3844. @findex float
  3845. @findex long double
  3846.  
  3847. @dfn{Floating point} is the binary analogue of scientific notation:
  3848. internally it represents a number as a fraction and a binary exponent; the
  3849. value is that fraction multiplied by the specified power of 2.
  3850.  
  3851. For instance, to represent 6, the fraction would be 0.75 and the
  3852. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3853. meaning 0.75 * 8.  The value 1.5 would use 0.75 as the fraction and 1
  3854. as the exponent.  The value 0.75 would use 0.75 as the fraction and 0
  3855. as the exponent.  The value 0.375 would use 0.75 as the fraction and
  3856. -1 as the exponent.
  3857.  
  3858. These binary exponents are used by machine instructions.  You can
  3859. write a floating-point constant this way if you wish, using
  3860. hexadecimal; but normally we write floating-point numbers in decimal.
  3861. @xref{Floating Constants}.
  3862.  
  3863. C has three floating-point data types:
  3864.  
  3865. @table @code
  3866. @item double
  3867. ``Double-precision'' floating point, which uses 64 bits.  This is the
  3868. normal floating-point type, and modern computers normally do
  3869. their floating-point computations in this type, or some wider type.
  3870. Except when there is a special reason to do otherwise, this is the
  3871. type to use for floating-point values.
  3872.  
  3873. @item float
  3874. ``Single-precision'' floating point, which uses 32 bits.  It is useful
  3875. for floating-point values stored in structures and arrays, to save
  3876. space when the full precision of @code{double} is not needed.  In
  3877. addition, single-precision arithmetic is faster on some computers, and
  3878. occasionally that is useful.  But not often---most programs don't use
  3879. the type @code{float}.
  3880.  
  3881. C would be cleaner if @code{float} were the name of the type we
  3882. use for most floating-point values; however, for historical reasons,
  3883. that's not so.
  3884.  
  3885. @item long double
  3886. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3887. precision, depending on the machine in use.  On some machines, which
  3888. have no floating-point format wider than @code{double}, this is
  3889. equivalent to @code{double}.
  3890. @end table
  3891.  
  3892. Floating-point arithmetic raises many subtle issues.  @xref{Floating
  3893. Point in Depth}, for more information.
  3894.  
  3895. @node Complex Data Types
  3896. @section Complex Data Types
  3897. @cindex complex numbers
  3898. @cindex types, complex
  3899. @cindex @code{_Complex} keyword
  3900. @cindex @code{__complex__} keyword
  3901. @findex _Complex
  3902. @findex __complex__
  3903.  
  3904. Complex numbers can include both a real part and an imaginary part.
  3905. The numeric constants covered above have real-numbered values.  An
  3906. imaginary-valued constant is an ordinary real-valued constant followed
  3907. by @samp{i}.
  3908.  
  3909. To declare numeric variables as complex, use the @code{_Complex}
  3910. keyword.@footnote{For compatibility with older versions of GNU C, the
  3911. keyword @code{__complex__} is also allowed.  Going forward, however,
  3912. use the new @code{_Complex} keyword as defined in ISO C11.}  The
  3913. standard C complex data types are floating point,
  3914.  
  3915. @example
  3916. _Complex float foo;
  3917. _Complex double bar;
  3918. _Complex long double quux;
  3919. @end example
  3920.  
  3921. @noindent
  3922. but GNU C supports integer complex types as well.
  3923.  
  3924. Since @code{_Complex} is a keyword just like @code{float} and
  3925. @code{double} and @code{long}, the keywords can appear in any order,
  3926. but the order shown above seems most logical.
  3927.  
  3928. GNU C supports constants for complex values; for instance, @code{4.0 +
  3929. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3930. @xref{Imaginary Constants}.
  3931.  
  3932. To pull the real and imaginary parts of the number back out, GNU C
  3933. provides the keywords @code{__real__} and @code{__imag__}:
  3934.  
  3935. @example
  3936. _Complex double foo = 4.0 + 3.0i;
  3937.  
  3938. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3939. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3940. @end example
  3941.  
  3942. @noindent
  3943. Standard C does not include these keywords, and instead relies on
  3944. functions defined in @code{complex.h} for accessing the real and
  3945. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3946. @code{creall} extract the real part of a float, double, or long double
  3947. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3948. @code{cimagl} extract the imaginary part.
  3949.  
  3950. @cindex complex conjugation
  3951. GNU C also defines @samp{~} as an operator for complex conjugation,
  3952. which means negating the imaginary part of a complex number:
  3953.  
  3954. @example
  3955. _Complex double foo = 4.0 + 3.0i;
  3956. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3957. @end example
  3958.  
  3959. @noindent
  3960. For standard C compatibility, you can use the appropriate library
  3961. function: @code{conjf}, @code{conj}, or @code{confl}.
  3962.  
  3963. @node The Void Type
  3964. @section The Void Type
  3965. @cindex void type
  3966. @cindex type, void
  3967. @findex void
  3968.  
  3969. The data type @code{void} is a dummy---it allows no operations.  It
  3970. really means ``no value at all.''  When a function is meant to return
  3971. no value, we write @code{void} for its return type.  Then
  3972. @code{return} statements in that function should not specify a value
  3973. (@pxref{return Statement}).  Here's an example:
  3974.  
  3975. @example
  3976. void
  3977. print_if_positive (double x, double y)
  3978. @{
  3979.   if (x <= 0)
  3980.     return;
  3981.   if (y <= 0)
  3982.     return;
  3983.   printf ("Next point is (%f,%f)\n", x, y);
  3984. @}
  3985. @end example
  3986.  
  3987. A @code{void}-returning function is comparable to what some other languages
  3988. call a ``procedure'' instead of a ``function.''
  3989.  
  3990. @c ??? Already presented
  3991. @c @samp{%f} in an output template specifies to format a @code{double} value
  3992. @c as a decimal number, using a decimal point if needed.
  3993.  
  3994. @node Other Data Types
  3995. @section Other Data Types
  3996.  
  3997. Beyond the primitive types, C provides several ways to construct new
  3998. data types.  For instance, you can define @dfn{pointers}, values that
  3999. represent the addresses of other data (@pxref{Pointers}).  You can
  4000. define @dfn{structures}, as in many other languages
  4001. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  4002. to look at the same memory space (@pxref{Unions}).  @dfn{Enumerations}
  4003. are collections of named integer codes (@pxref{Enumeration Types}).
  4004.  
  4005. @dfn{Array types} in C are used for allocating space for objects,
  4006. but C does not permit operating on an array value as a whole.  @xref{Arrays}.
  4007.  
  4008. @node Type Designators
  4009. @section Type Designators
  4010. @cindex type designator
  4011.  
  4012. Some C constructs require a way to designate a specific data type
  4013. independent of any particular variable or expression which has that
  4014. type.  The way to do this is with a @dfn{type designator}.  The
  4015. constucts that need one include casts (@pxref{Explicit Type
  4016. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  4017.  
  4018. We also use type designators to talk about the type of a value in C,
  4019. so you will see many type designators in this manual.  When we say,
  4020. ``The value has type @code{int},'' @code{int} is a type designator.
  4021.  
  4022. To make the designator for any type, imagine a variable declaration
  4023. for a variable of that type and delete the variable name and the final
  4024. semicolon.
  4025.  
  4026. For example, to designate the type of full-word integers, we start
  4027. with the declaration for a variable @code{foo} with that type,
  4028. which is this:
  4029.  
  4030. @example
  4031. int foo;
  4032. @end example
  4033.  
  4034. @noindent
  4035. Then we delete the variable name @code{foo} and the semicolon, leaving
  4036. @code{int}---exactly the keyword used in such a declaration.
  4037. Therefore, the type designator for this type is @code{int}.
  4038.  
  4039. What about long unsigned integers?  From the declaration
  4040.  
  4041. @example
  4042. unsigned long int foo;
  4043. @end example
  4044.  
  4045. @noindent
  4046. we determine that the designator is @code{unsigned long int}.
  4047.  
  4048. Following this procedure, the designator for any primitive type is
  4049. simply the set of keywords which specifies that type in a declaration.
  4050. The same is true for compound types such as structures, unions, and
  4051. enumerations.
  4052.  
  4053. Designators for pointer types do follow the rule of deleting the
  4054. variable name and semicolon, but the result is not so simple.
  4055. @xref{Pointer Type Designators}, as part of the chapter about
  4056. pointers.  @xref{Array Type Designators}), for designators for array
  4057. types.
  4058.  
  4059. To understand what type a designator stands for, imagine a variable
  4060. name inserted into the right place in the designator to make a valid
  4061. declaration.  What type would that variable be declared as?  That is the
  4062. type the designator designates.
  4063.  
  4064. @node Constants
  4065. @chapter Constants
  4066. @cindex constants
  4067.  
  4068. A @dfn{constant} is an expression that stands for a specific value by
  4069. explicitly representing the desired value.  C allows constants for
  4070. numbers, characters, and strings.  We have already seen numeric and
  4071. string constants in the examples.
  4072.  
  4073. @menu
  4074. * Integer Constants::            Literal integer values.
  4075. * Integer Const Type::           Types of literal integer values.
  4076. * Floating Constants::           Literal floating-point values.
  4077. * Imaginary Constants::          Literal imaginary number values.
  4078. * Invalid Numbers::              Avoiding preprocessing number misconceptions.
  4079. * Character Constants::          Literal character values.
  4080. * String Constants::             Literal string values.
  4081. * UTF-8 String Constants::       Literal UTF-8 string values.
  4082. * Unicode Character Codes::      Unicode characters represented
  4083.                                   in either UTF-16 or UTF-32.
  4084. * Wide Character Constants::     Literal characters values larger than 8 bits.
  4085. * Wide String Constants::        Literal string values made up of
  4086.                                   16- or 32-bit characters.
  4087. @end menu
  4088.  
  4089. @node Integer Constants
  4090. @section Integer Constants
  4091. @cindex integer constants
  4092. @cindex constants, integer
  4093.  
  4094. An integer constant consists of a number to specify the value,
  4095. followed optionally by suffix letters to specify the data type.
  4096.  
  4097. The simplest integer constants are numbers written in base 10
  4098. (decimal), such as @code{5}, @code{77}, and @code{403}.  A decimal
  4099. constant cannot start with the character @samp{0} (zero) because
  4100. that makes the constant octal.
  4101.  
  4102. You can get the effect of a negative integer constant by putting a
  4103. minus sign at the beginning.  Grammatically speaking, that is an
  4104. arithmetic expression rather than a constant, but it behaves just like
  4105. a true constant.
  4106.  
  4107. Integer constants can also be written in octal (base 8), hexadecimal
  4108. (base 16), or binary (base 2).  An octal constant starts with the
  4109. character @samp{0} (zero), followed by any number of octal digits
  4110. (@samp{0} to @samp{7}):
  4111.  
  4112. @example
  4113. 0      // @r{zero}
  4114. 077    // @r{63}
  4115. 0403   // @r{259}
  4116. @end example
  4117.  
  4118. @noindent
  4119. Pedantically speaking, the constant @code{0} is an octal constant, but
  4120. we can think of it as decimal; it has the same value either way.
  4121.  
  4122. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  4123. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  4124. through @samp{f} in upper or lower case):
  4125.  
  4126. @example
  4127. 0xff   // @r{255}
  4128. 0XA0   // @r{160}
  4129. 0xffFF // @r{65535}
  4130. @end example
  4131.  
  4132. @cindex binary integer constants
  4133. A binary constant starts with @samp{0b} (upper or lower case) followed
  4134. by bits (each represented by the characters @samp{0} or @samp{1}):
  4135.  
  4136. @example
  4137. 0b101  // @r{5}
  4138. @end example
  4139.  
  4140. Binary constants are a GNU C extension, not part of the C standard.
  4141.  
  4142. Sometimes a space is needed after an integer constant to avoid
  4143. lexical confusion with the following tokens.  @xref{Invalid Numbers}.
  4144.  
  4145. @node Integer Const Type
  4146. @section Integer Constant Data Types
  4147. @cindex integer constant data types
  4148. @cindex constant data types, integer
  4149. @cindex types of integer constants
  4150.  
  4151. The type of an integer constant is normally @code{int}, if the value
  4152. fits in that type, but here are the complete rules.  The type
  4153. of an integer constant is the first one in this sequence that can
  4154. properly represent the value,
  4155.  
  4156. @enumerate
  4157. @item
  4158. @code{int}
  4159. @item
  4160. @code{unsigned int}
  4161. @item
  4162. @code{long int}
  4163. @item
  4164. @code{unsigned long int}
  4165. @item
  4166. @code{long long int}
  4167. @item
  4168. @code{unsigned long long int}
  4169. @end enumerate
  4170.  
  4171. @noindent
  4172. and that isn't excluded by the following rules.
  4173.  
  4174. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  4175. first two types (non-@code{long}).
  4176.  
  4177. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  4178. first four types (non-@code{long long}).
  4179.  
  4180. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  4181. the signed types.
  4182.  
  4183. Otherwise, if the constant is decimal, that excludes the unsigned
  4184. types.
  4185. @c ### This said @code{unsigned int} is excluded.
  4186. @c ### See 17 April 2016
  4187.  
  4188. Here are some examples of the suffixes.
  4189.  
  4190. @example
  4191. 3000000000u      // @r{three billion as @code{unsigned int}.}
  4192. 0LL              // @r{zero as a @code{long long int}.}
  4193. 0403l            // @r{259 as a @code{long int}.}
  4194. @end example
  4195.  
  4196. Suffixes in integer constants are rarely used.  When the precise type
  4197. is important, it is cleaner to convert explicitly (@pxref{Explicit
  4198. Type Conversion}).
  4199.  
  4200. @xref{Integer Types}.
  4201.  
  4202. @node Floating Constants
  4203. @section Floating-Point Constants
  4204. @cindex floating-point constants
  4205. @cindex constants, floating-point
  4206.  
  4207. A floating-point constant must have either a decimal point, an
  4208. exponent-of-ten, or both; they distinguish it from an integer
  4209. constant.
  4210.  
  4211. To indicate an exponent, write @samp{e} or @samp{E}.  The exponent
  4212. value follows.  It is always written as a decimal number; it can
  4213. optionally start with a sign.  The exponent @var{n} means to multiply
  4214. the constant's value by ten to the @var{n}th power.
  4215.  
  4216. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  4217. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  4218. writing a floating-point number whose value is 1500.  They are all
  4219. equivalent.
  4220.  
  4221. Here are more examples with decimal points:
  4222.  
  4223. @example
  4224. 1.0
  4225. 1000.
  4226. 3.14159
  4227. .05
  4228. .0005
  4229. @end example
  4230.  
  4231. For each of them, here are some equivalent constants written with
  4232. exponents:
  4233.  
  4234. @example
  4235. 1e0, 1.0000e0
  4236. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  4237. 3.14159e0
  4238. 5e-2, .0005e+2, 5E-2, .0005E2
  4239. .05e-2
  4240. @end example
  4241.  
  4242. A floating-point constant normally has type @code{double}.  You can
  4243. force it to type @code{float} by adding @samp{f} or @samp{F}
  4244. at the end.  For example,
  4245.  
  4246. @example
  4247. 3.14159f
  4248. 3.14159e0f
  4249. 1000.f
  4250. 100E1F
  4251. .0005f
  4252. .05e-2f
  4253. @end example
  4254.  
  4255. Likewise, @samp{l} or @samp{L} at the end forces the constant
  4256. to type @code{long double}.
  4257.  
  4258. You can use exponents in hexadecimal floating constants, but since
  4259. @samp{e} would be interpreted as a hexadecimal digit, the character
  4260. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  4261.  
  4262. The exponent in a hexadecimal floating constant is a possibly-signed
  4263. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  4264. multiply into the number.
  4265.  
  4266. Here are some examples:
  4267.  
  4268. @example
  4269. @group
  4270. 0xAp2        // @r{40 in decimal}
  4271. 0xAp-1       // @r{5 in decimal}
  4272. 0x2.0Bp4     // @r{16.75 decimal}
  4273. 0xE.2p3      // @r{121 decimal}
  4274. 0x123.ABCp0  // @r{291.6708984375 in decimal}
  4275. 0x123.ABCp4  // @r{4666.734375 in decimal}
  4276. 0x100p-8     // @r{1}
  4277. 0x10p-4      // @r{1}
  4278. 0x1p+4       // @r{16}
  4279. 0x1p+8       // @r{256}
  4280. @end group
  4281. @end example
  4282.  
  4283. @xref{Floating-Point Data Types}.
  4284.  
  4285. @node Imaginary Constants
  4286. @section Imaginary Constants
  4287. @cindex imaginary constants
  4288. @cindex complex constants
  4289. @cindex constants, imaginary
  4290.  
  4291. A complex number consists of a real part plus an imaginary part.
  4292. (Either or both parts may be zero.)  This section explains how to
  4293. write numeric constants with imaginary values.  By adding these to
  4294. ordinary real-valued numeric constants, we can make constants with
  4295. complex values.
  4296.  
  4297. The simple way to write an imaginary-number constant is to attach the
  4298. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  4299. floating-point constant.  For example, @code{2.5fi} has type
  4300. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  4301. The four alternative suffix letters are all equivalent.
  4302.  
  4303. @cindex _Complex_I
  4304. The other way to write an imaginary constant is to multiply a real
  4305. constant by @code{_Complex_I}, which represents the imaginary number
  4306. i.  Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  4307. this clunky way is needed.
  4308.  
  4309. To write a complex constant with a nonzero real part and a nonzero
  4310. imaginary part, write the two separately and add them, like this:
  4311.  
  4312. @example
  4313. 4.0 + 3.0i
  4314. @end example
  4315.  
  4316. @noindent
  4317. That gives the value 4 + 3i, with type @code{_Complex double}.
  4318.  
  4319. Such a sum can include multiple real constants, or none.  Likewise, it
  4320. can include multiple imaginary constants, or none.  For example:
  4321.  
  4322. @example
  4323. _Complex double foo, bar, quux;
  4324.  
  4325. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  4326. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  4327. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  4328. @end example
  4329.  
  4330. @xref{Complex Data Types}.
  4331.  
  4332. @node Invalid Numbers
  4333. @section Invalid Numbers
  4334.  
  4335. Some number-like constructs which are not really valid as numeric
  4336. constants are treated as numbers in preprocessing directives.  If
  4337. these constructs appear outside of preprocessing, they are erroneous.
  4338. @xref{Preprocessing Tokens}.
  4339.  
  4340. Sometimes we need to insert spaces to separate tokens so that they
  4341. won't be combined into a single number-like construct.  For example,
  4342. @code{0xE+12} is a preprocessing number that is not a valid numeric
  4343. constant, so it is a syntax error.  If what we want is the three
  4344. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  4345.  
  4346. @node Character Constants
  4347. @section Character Constants
  4348. @cindex character constants
  4349. @cindex constants, character
  4350. @cindex escape sequence
  4351.  
  4352. A @dfn{character constant} is written with single quotes, as in
  4353. @code{'@var{c}'}.  In the simplest case, @var{c} is a single ASCII
  4354. character that the constant should represent.  The constant has type
  4355. @code{int}, and its value is the character code of that character.
  4356. For instance, @code{'a'} represents the character code for the letter
  4357. @samp{a}: 97, that is.
  4358.  
  4359. To put the @samp{'} character (single quote) in the character
  4360. constant, @dfn{quote} it with a backslash (@samp{\}).  This character
  4361. constant looks like @code{'\''}.  This sort of sequence, starting with
  4362. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  4363. here functions as a kind of @dfn{escape character}.
  4364.  
  4365. To put the @samp{\} character (backslash) in the character constant,
  4366. quote it likewise with @samp{\} (another backslash).  This character
  4367. constant looks like @code{'\\'}.
  4368.  
  4369. @cindex bell character
  4370. @cindex @samp{\a}
  4371. @cindex backspace
  4372. @cindex @samp{\b}
  4373. @cindex tab (ASCII character)
  4374. @cindex @samp{\t}
  4375. @cindex vertical tab
  4376. @cindex @samp{\v}
  4377. @cindex formfeed
  4378. @cindex @samp{\f}
  4379. @cindex newline
  4380. @cindex @samp{\n}
  4381. @cindex return (ASCII character)
  4382. @cindex @samp{\r}
  4383. @cindex escape (ASCII character)
  4384. @cindex @samp{\e}
  4385. Here are all the escape sequences that represent specific
  4386. characters in a character constant.  The numeric values shown are
  4387. the corresponding ASCII character codes, as decimal numbers.
  4388.  
  4389. @example
  4390. '\a' @result{} 7       /* @r{alarm, @kbd{CTRL-g}} */
  4391. '\b' @result{} 8       /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  4392. '\t' @result{} 9       /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  4393. '\n' @result{} 10      /* @r{newline, @kbd{CTRL-j}} */
  4394. '\v' @result{} 11      /* @r{vertical tab, @kbd{CTRL-k}} */
  4395. '\f' @result{} 12      /* @r{formfeed, @kbd{CTRL-l}} */
  4396. '\r' @result{} 13      /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  4397. '\e' @result{} 27      /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  4398. '\\' @result{} 92      /* @r{backslash character, @kbd{\}} */
  4399. '\'' @result{} 39      /* @r{singlequote character, @kbd{'}} */
  4400. '\"' @result{} 34      /* @r{doublequote character, @kbd{"}} */
  4401. '\?' @result{} 63      /* @r{question mark, @kbd{?}} */
  4402. @end example
  4403. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  4404. You can also write octal and hex character codes as
  4405. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}.  Decimal is not an
  4406. option here, so octal codes do not need to start with @samp{0}.
  4407. The character constant's value has type @code{int}.  However, the
  4408. character code is treated initially as a @code{char} value, which is
  4409. then converted to @code{int}.  If the character code is greater than
  4410. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  4411. on a platform where the type @code{char} is 8 bits long and signed.
  4412. @node String Constants
  4413. @section String Constants
  4414. @cindex string constants
  4415. @cindex constants, string
  4416. A @dfn{string constant} represents a series of characters.  It starts
  4417. with @samp{"} and ends with @samp{"}; in between are the contents of
  4418. the string.  Quoting special characters such as @samp{"}, @samp{\} and
  4419. newline in the contents works in string constants as in character
  4420. constants.  In a string constant, @samp{'} does not need to be quoted.
  4421. A string constant defines an array of characters which contains the
  4422. specified characters followed by the null character (code 0).  Using
  4423. the string constant is equivalent to using the name of an array with
  4424. those contents.  In simple cases, the length in bytes of the string
  4425. constant is one greater than the number of characters written in it.
  4426. As with any array in C, using the string constant in an expression
  4427. converts the array to a pointer (@pxref{Pointers}) to the array's
  4428. first element (@pxref{Accessing Array Elements}).  This pointer will
  4429. have type @code{char *} because it points to an element of type
  4430. @code{char}.  @code{char *} is an example of a type designator for a
  4431. pointer type (@pxref{Pointer Type Designators}).  That type is used
  4432. for strings generally, not just the strings expressed as constants
  4433. in a program.
  4434. Thus, the string constant @code{"Foo!"} is almost
  4435. equivalent to declaring an array like this
  4436. @example
  4437. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  4438. @end example
  4439. @noindent
  4440. and then using @code{string_array_1} in the program.  There
  4441. are two differences, however:
  4442. @itemize @bullet
  4443. @item
  4444. The string constant doesn't define a name for the array.
  4445. @item
  4446. The string constant is probably stored in a read-only area of memory.
  4447. @end itemize
  4448. Newlines are not allowed in the text of a string constant.  The motive
  4449. for this prohibition is to catch the error of omitting the closing
  4450. @samp{"}.  To put a newline in a constant string, write it as
  4451. @samp{\n} in the string constant.
  4452. A real null character in the source code inside a string constant
  4453. causes a warning.  To put a null character in the middle of a string
  4454. constant, write @samp{\0} or @samp{\000}.
  4455. Consecutive string constants are effectively concatenated.  Thus,
  4456. @example
  4457. "Fo" "o!"   @r{is equivalent to}   "Foo!"
  4458. @end example
  4459. This is useful for writing a string containing multiple lines,
  4460. like this:
  4461. @example
  4462. "This message is so long that it needs more than\n"
  4463. "a single line of text.  C does not allow a newline\n"
  4464. "to represent itself in a string constant, so we have to\n"
  4465. "write \\n to put it in the string.  For readability of\n"
  4466. "the source code, it is advisable to put line breaks in\n"
  4467. "the source where they occur in the contents of the\n"
  4468. "constant.\n"
  4469. @end example
  4470. The sequence of a backslash and a newline is ignored anywhere
  4471. in a C program, and that includes inside a string constant.
  4472. Thus, you can write multi-line string constants this way:
  4473. @example
  4474. "This is another way to put newlines in a string constant\n\
  4475. and break the line after them in the source code."
  4476. @end example
  4477. @noindent
  4478. However, concatenation is the recommended way to do this.
  4479. You can also write perverse string constants like this,
  4480. @example
  4481. "Fo\
  4482. o!"
  4483. @end example
  4484. @noindent
  4485. but don't do that---write it like this instead:
  4486. @example
  4487. "Foo!"
  4488. @end example
  4489. Be careful to avoid passing a string constant to a function that
  4490. modifies the string it receives.  The memory where the string constant
  4491. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  4492. signal that normally terminates the function (@pxref{Signals}.  Even
  4493. worse, the memory may not be read-only.  Then the function might
  4494. modify the string constant, thus spoiling the contents of other string
  4495. constants that are supposed to contain the same value and are unified
  4496. by the compiler.
  4497. @node UTF-8 String Constants
  4498. @section UTF-8 String Constants
  4499. @cindex UTF-8 String Constants
  4500. Writing @samp{u8} immediately before a string constant, with no
  4501. intervening space, means to represent that string in UTF-8 encoding as
  4502. a sequence of bytes.  UTF-8 represents ASCII characters with a single
  4503. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  4504. as multibyte sequences.  Here is an example of a UTF-8 constant:
  4505. @example
  4506. u8"A cónstàñt"
  4507. @end example
  4508. This constant occupies 13 bytes plus the terminating null,
  4509. because each of the accented letters is a two-byte sequence.
  4510. Concatenating an ordinary string with a UTF-8 string conceptually
  4511. produces another UTF-8 string.  However, if the ordinary string
  4512. contains character codes 128 and up, the results cannot be relied on.
  4513. @node Unicode Character Codes
  4514. @section Unicode Character Codes
  4515. @cindex Unicode character codes
  4516. @cindex universal character names
  4517. You can specify Unicode characters, for individual character constants
  4518. or as part of string constants (@pxref{String Constants}), using
  4519. escape sequences.  Use the @samp{\u} escape sequence with a 16-bit
  4520. hexadecimal Unicode character code.  If the code value is too big for
  4521. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  4522. Unicode character code.  (These codes are called @dfn{universal
  4523. character names}.)  For example,
  4524. @example
  4525. \u6C34      /* @r{16-bit code (UTF-16)} */
  4526. \U0010ABCD  /* @r{32-bit code (UTF-32)} */
  4527. @end example
  4528. @noindent
  4529. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  4530. Constants}).  For instance,
  4531. @example
  4532. u8"fóó \u6C34 \U0010ABCD"
  4533. @end example
  4534.  You can also use them in wide character constants (@pxref{Wide
  4535. Character Constants}), like this:
  4536. @example
  4537. u'\u6C34'      /* @r{16-bit code} */
  4538. U'\U0010ABCD'  /* @r{32-bit code} */
  4539. @end example
  4540. @noindent
  4541. and in wide string constants (@pxref{Wide String Constants}), like
  4542. this:
  4543. @example
  4544. u"\u6C34\u6C33"  /* @r{16-bit code} */
  4545. U"\U0010ABCD"    /* @r{32-bit code} */
  4546. @end example
  4547. Codes in the range of @code{D800} through @code{DFFF} are not valid
  4548. in Unicode.  Codes less than @code{00A0} are also forbidden, except for
  4549. @code{0024}, @code{0040}, and @code{0060}; these characters are
  4550. actually ASCII control characters, and you can specify them with other
  4551. escape sequences (@pxref{Character Constants}).
  4552. @node Wide Character Constants
  4553. @section Wide Character Constants
  4554. @cindex wide character constants
  4555. @cindex constants, wide character
  4556. A @dfn{wide character constant} represents characters with more than 8
  4557. bits of character code.  This is an obscure feature that we need to
  4558. document but that you probably won't ever use.  If you're just
  4559. learning C, you may as well skip this section.
  4560. The original C wide character constant looks like @samp{L} (upper
  4561. case!) followed immediately by an ordinary character constant (with no
  4562. intervening space).  Its data type is @code{wchar_t}, which is an
  4563. alias defined in @file{stddef.h} for one of the standard integer
  4564. types.  Depending on the platform, it could be 16 bits or 32 bits.  If
  4565. it is 16 bits, these character constants use the UTF-16 form of
  4566. Unicode; if 32 bits, UTF-32.
  4567. There are also Unicode wide character constants which explicitly
  4568. specify the width.  These constants start with @samp{u} or @samp{U}
  4569. instead of @samp{L}.  @samp{u} specifies a 16-bit Unicode wide
  4570. character constant, and @samp{U} a 32-bit Unicode wide character
  4571. constant.  Their types are, respectively, @code{char16_t} and
  4572. @w{@code{char32_t}}; they are declared in the header file
  4573. @file{uchar.h}.  These character constants are valid even if
  4574. @file{uchar.h} is not included, but some uses of them may be
  4575. inconvenient without including it to declare those type names.
  4576. The character represented in a wide character constant can be an
  4577. ordinary ASCII character.  @code{L'a'}, @code{u'a'} and @code{U'a'}
  4578. are all valid, and they are all equal to @code{'a'}.
  4579. In all three kinds of wide character constants, you can write a
  4580. non-ASCII Unicode character in the constant itself; the constant's
  4581. value is the character's Unicode character code.  Or you can specify
  4582. the Unicode character with an escape sequence (@pxref{Unicode
  4583. Character Codes}).
  4584. @node Wide String Constants
  4585. @section Wide String Constants
  4586. @cindex wide string constants
  4587. @cindex constants, wide string
  4588. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  4589. characters.  They are rarely used; if you're just
  4590. learning C, you may as well skip this section.
  4591. There are three kinds of wide string constants, which differ in the
  4592. data type used for each character in the string.  Each wide string
  4593. constant is equivalent to an array of integers, but the data type of
  4594. those integers depends on the kind of wide string.  Using the constant
  4595. in an expression will convert the array to a pointer to its first
  4596. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  4597. For each kind of wide string constant, we state here what type that
  4598. pointer will be.
  4599. @table @code
  4600. @item char16_t
  4601. This is a 16-bit Unicode wide string constant: each element is a
  4602. 16-bit Unicode character code with type @code{char16_t}, so the string
  4603. has the pointer type @code{char16_t@ *}.  (That is a type designator;
  4604. @pxref{Pointer Type Designators}.)  The constant is written as
  4605. @samp{u} (which must be lower case) followed (with no intervening
  4606. space) by a string constant with the usual syntax.
  4607. @item char32_t
  4608. This is a 32-bit Unicode wide string constant: each element is a
  4609. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  4610. It's written as @samp{U} (which must be upper case) followed (with no
  4611. intervening space) by a string constant with the usual syntax.
  4612. @item wchar_t
  4613. This is the original kind of wide string constant.  It's written as
  4614. @samp{L} (which must be upper case) followed (with no intervening
  4615. space) by a string constant with the usual syntax, and the string has
  4616. type @code{wchar_t@ *}.
  4617. The width of the data type @code{wchar_t} depends on the target
  4618. platform, which makes this kind of wide string somewhat less useful
  4619. than the newer kinds.
  4620. @end table
  4621. @code{char16_t} and @code{char32_t} are declared in the header file
  4622. @file{uchar.h}.  @code{wchar_t} is declared in @file{stddef.h}.
  4623. Consecutive wide string constants of the same kind concatenate, just
  4624. like ordinary string constants.  A wide string constant concatenated
  4625. with an ordinary string constant results in a wide string constant.
  4626. You can't concatenate two wide string constants of different kinds.
  4627. You also can't concatenate a wide string constant (of any kind) with a
  4628. UTF-8 string constant.
  4629. @node Type Size
  4630. @chapter Type Size
  4631. @cindex type size
  4632. @cindex size of type
  4633. @findex sizeof
  4634. Each data type has a @dfn{size}, which is the number of bytes
  4635. (@pxref{Storage}) that it occupies in memory.  To refer to the size in
  4636. a C program, use @code{sizeof}.  There are two ways to use it:
  4637. @table @code
  4638. @item sizeof @var{expression}
  4639. This gives the size of @var{expression}, based on its data type.  It
  4640. does not calculate the value of @var{expression}, only its size, so if
  4641. @var{expression} includes side effects or function calls, they do not
  4642. happen.  Therefore, @code{sizeof} is always a compile-time operation
  4643. that has zero run-time cost.
  4644. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  4645. operand of @code{sizeof}.
  4646. For example,
  4647. @example
  4648. double a;
  4649. i = sizeof a + 10;
  4650. @end example
  4651. @noindent
  4652. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  4653. Here's how to determine the number of elements in an array
  4654. @code{array}:
  4655. @example
  4656. (sizeof array / sizeof array[0])
  4657. @end example
  4658.  
  4659. @noindent
  4660. The expression @code{sizeof array} gives the size of the array, not
  4661. the size of a pointer to an element.  However, if @var{expression} is
  4662. a function parameter that was declared as an array, that
  4663. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  4664. the result is the size of that pointer.
  4665.  
  4666. @item sizeof (@var{type})
  4667. This gives the size of @var{type}.
  4668. For example,
  4669.  
  4670. @example
  4671. i = sizeof (double) + 10;
  4672. @end example
  4673.  
  4674. @noindent
  4675. is equivalent to the previous example.
  4676.  
  4677. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  4678. Types}), nor @code{void}.  Using it on a function type gives 1 in GNU
  4679. C, which makes adding an integer to a function pointer work as desired
  4680. (@pxref{Pointer Arithmetic}).
  4681. @end table
  4682.  
  4683. @strong{Warning}: When you use @code{sizeof} with a type
  4684. instead of an expression, you must write parentheses around the type.
  4685.  
  4686. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  4687. (@pxref{Explicit Type Conversion}), you must write parentheses around
  4688. the cast expression to avoid an ambiguity in the grammar of C@.
  4689. Specifically,
  4690.  
  4691. @example
  4692. sizeof (int) -x
  4693. @end example
  4694.  
  4695. @noindent
  4696. parses as
  4697.  
  4698. @example
  4699. (sizeof (int)) - x
  4700. @end example
  4701.  
  4702. @noindent
  4703. If what you want is
  4704.  
  4705. @example
  4706. sizeof ((int) -x)
  4707. @end example
  4708.  
  4709. @noindent
  4710. you must write it that way, with parentheses.
  4711.  
  4712. The data type of the value of the @code{sizeof} operator is always one
  4713. of the unsigned integer types; which one of those types depends on the
  4714. machine.  The header file @code{stddef.h} defines the typedef name
  4715. @code{size_t} as an alias for this type.  @xref{Defining Typedef
  4716. Names}.
  4717.  
  4718. @node Pointers
  4719. @chapter Pointers
  4720. @cindex pointers
  4721.  
  4722. Among high-level languages, C is rather low level, close to the
  4723. machine.  This is mainly because it has explicit @dfn{pointers}.  A
  4724. pointer value is the numeric address of data in memory.  The type of
  4725. data to be found at that address is specified by the data type of the
  4726. pointer itself.  The unary operator @samp{*} gets the data that a
  4727. pointer points to---this is called @dfn{dereferencing the pointer}.
  4728.  
  4729. C also allows pointers to functions, but since there are some
  4730. differences in how they work, we treat them later.  @xref{Function
  4731. Pointers}.
  4732.  
  4733. @menu
  4734. * Address of Data::              Using the ``address-of'' operator.
  4735. * Pointer Types::                For each type, there is a pointer type.
  4736. * Pointer Declarations::         Declaring variables with pointer types.
  4737. * Pointer Type Designators::     Designators for pointer types.
  4738. * Pointer Dereference::          Accessing what a pointer points at.
  4739. * Null Pointers::                Pointers which do not point to any object.
  4740. * Invalid Dereference::          Dereferencing null or invalid pointers.
  4741. * Void Pointers::                Totally generic pointers, can cast to any.
  4742. * Pointer Comparison::           Comparing memory address values.
  4743. * Pointer Arithmetic::           Computing memory address values.
  4744. * Pointers and Arrays::          Using pointer syntax instead of array syntax.
  4745. * Pointer Arithmetic Low Level:: More about computing memory address values.
  4746. * Pointer Increment/Decrement::  Incrementing and decrementing pointers.
  4747. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  4748. * Pointer-Integer Conversion::   Converting pointer types to integer types.
  4749. * Printing Pointers::            Using @code{printf} for a pointer's value.
  4750. @end menu
  4751.  
  4752. @node Address of Data
  4753. @section Address of Data
  4754.  
  4755. @cindex address-of operator
  4756. The most basic way to make a pointer is with the ``address-of''
  4757. operator, @samp{&}.  Let's suppose we have these variables available:
  4758.  
  4759. @example
  4760. int i;
  4761. double a[5];
  4762. @end example
  4763.  
  4764. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  4765. value that points to @code{i}'s location---and @code{&a[3]} gives the
  4766. address of the element 3 of @code{a}.  (It is actually the fourth
  4767. element in the array, since the first element has index 0.)
  4768.  
  4769. The address-of operator is unusual because it operates on a place to
  4770. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  4771. stored there.  (The left argument of a simple assignment is unusual in
  4772. the same way.)  You can use it on any lvalue except a bit field
  4773. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  4774. Constructors}).
  4775.  
  4776.  
  4777. @node Pointer Types
  4778. @section Pointer Types
  4779.  
  4780. For each data type @var{t}, there is a type for pointers to type
  4781. @var{t}.  For these variables,
  4782.  
  4783. @example
  4784. int i;
  4785. double a[5];
  4786. @end example
  4787.  
  4788. @itemize @bullet
  4789. @item
  4790. @code{i} has type @code{int}; we say
  4791. @code{&i} is a ``pointer to @code{int}.''
  4792.  
  4793. @item
  4794. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  4795. arrays of five @code{double}s.''
  4796.  
  4797. @item
  4798. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  4799. to @code{double}.''
  4800. @end itemize
  4801.  
  4802. @node Pointer Declarations
  4803. @section Pointer-Variable Declarations
  4804.  
  4805. The way to declare that a variable @code{foo} points to type @var{t} is
  4806.  
  4807. @example
  4808. @var{t} *foo;
  4809. @end example
  4810.  
  4811. To remember this syntax, think ``if you dereference @code{foo}, using
  4812. the @samp{*} operator, what you get is type @var{t}.  Thus, @code{foo}
  4813. points to type @var{t}.''
  4814.  
  4815. Thus, we can declare variables that hold pointers to these three
  4816. types, like this:
  4817.  
  4818. @example
  4819. int *ptri;            /* @r{Pointer to @code{int}.} */
  4820. double *ptrd;         /* @r{Pointer to @code{double}.} */
  4821. double (*ptrda)[5];   /* @r{Pointer to @code{double[5]}.} */
  4822. @end example
  4823.  
  4824. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  4825. @code{int}.''  @samp{double (*ptrda)[5];} means, ``if you dereference
  4826. @code{ptrda}, then subscript it by an integer less than 5, you get a
  4827. @code{double}.''  The parentheses express the point that you would
  4828. dereference it first, then subscript it.
  4829.  
  4830. Contrast the last one with this:
  4831.  
  4832. @example
  4833. double *aptrd[5];     /* @r{Array of five pointers to @code{double}.} */
  4834. @end example
  4835.  
  4836. @noindent
  4837. Because @samp{*} has higher syntactic precedence than subscripting,
  4838. you would subscript @code{aptrd} then dereference it.  Therefore, it
  4839. declares an array of pointers, not a pointer.
  4840.  
  4841. @node Pointer Type Designators
  4842. @section Pointer-Type Designators
  4843.  
  4844. Every type in C has a designator; you make it by deleting the variable
  4845. name and the semicolon from a declaration (@pxref{Type
  4846. Designators}).  Here are the designators for the pointer
  4847. types of the example declarations in the previous section:
  4848.  
  4849. @example
  4850. int *           /* @r{Pointer to @code{int}.} */
  4851. double *        /* @r{Pointer to @code{double}.} */
  4852. double (*)[5]   /* @r{Pointer to @code{double[5]}.} */
  4853. @end example
  4854.  
  4855. Remember, to understand what type a designator stands for, imagine the
  4856. variable name that would be in the declaration, and figure out what
  4857. type it would declare that variable with.  @code{double (*)[5]} can
  4858. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  4859. which, when dereferenced, gives an array of 5 @code{double}s.
  4860.  
  4861. @node Pointer Dereference
  4862. @section Dereferencing Pointers
  4863. @cindex dereferencing pointers
  4864. @cindex pointer dereferencing
  4865.  
  4866. The main use of a pointer value is to @dfn{dereference it} (access the
  4867. data it points at) with the unary @samp{*} operator.  For instance,
  4868. @code{*&i} is the value at @code{i}'s address---which is just
  4869. @code{i}.  The two expressions are equivalent, provided @code{&i} is
  4870. valid.
  4871.  
  4872. A pointer-dereference expression whose type is data (not a function)
  4873. is an lvalue.
  4874.  
  4875. Pointers become really useful when we store them somewhere and use
  4876. them later.  Here's a simple example to illustrate the practice:
  4877.  
  4878. @example
  4879. @{
  4880.  int i;
  4881.  int *ptr;
  4882.  
  4883.  ptr = &i;
  4884.  
  4885.  i = 5;
  4886.  
  4887.  @r{@dots{}}
  4888.  
  4889.  return *ptr;   /* @r{Returns 5, fetched from @code{i}.}  */
  4890. @}
  4891. @end example
  4892.  
  4893. This shows how to declare the variable @code{ptr} as type
  4894. @code{int *} (pointer to @code{int}), store a pointer value into it
  4895. (pointing at @code{i}), and use it later to get the value of the
  4896. object it points at (the value in @code{i}).
  4897.  
  4898. If anyone can provide a useful example which is this basic,
  4899. I would be grateful.
  4900.  
  4901. @node Null Pointers
  4902. @section Null Pointers
  4903. @cindex null pointers
  4904. @cindex pointers, null
  4905.  
  4906. @c ???stdio loads sttddef
  4907.  
  4908. A pointer value can be @dfn{null}, which means it does not point to
  4909. any object.  The cleanest way to get a null pointer is by writing
  4910. @code{NULL}, a standard macro defined in @file{stddef.h}.  You can
  4911. also do it by casting 0 to the desired pointer type, as in
  4912. @code{(char *) 0}.  (The cast operator performs explicit type conversion;
  4913. @xref{Explicit Type Conversion}.)
  4914.  
  4915. You can store a null pointer in any lvalue whose data type
  4916. is a pointer type:
  4917.  
  4918. @example
  4919. char *foo;
  4920. foo = NULL;
  4921. @end example
  4922.  
  4923. These two, if consecutive, can be combined into a declaration with
  4924. initializer,
  4925.  
  4926. @example
  4927. char *foo = NULL;
  4928. @end example
  4929.  
  4930. You can also explicitly cast @code{NULL} to the specific pointer type
  4931. you want---it makes no difference.
  4932.  
  4933. @example
  4934. char *foo;
  4935. foo = (char *) NULL;
  4936. @end example
  4937.  
  4938. To test whether a pointer is null, compare it with zero or
  4939. @code{NULL}, as shown here:
  4940.  
  4941. @example
  4942. if (p != NULL)
  4943.  /* @r{@code{p} is not null.}  */
  4944.  operate (p);
  4945. @end example
  4946.  
  4947. Since testing a pointer for not being null is basic and frequent, all
  4948. but beginners in C will understand the conditional without need for
  4949. @code{!= NULL}:
  4950.  
  4951. @example
  4952. if (p)
  4953.  /* @r{@code{p} is not null.}  */
  4954.  operate (p);
  4955. @end example
  4956.  
  4957. @node Invalid Dereference
  4958. @section Dereferencing Null or Invalid Pointers
  4959.  
  4960. Trying to dereference a null pointer is an error.  On most platforms,
  4961. it generally causes a signal, usually @code{SIGSEGV}
  4962. (@pxref{Signals}).
  4963.  
  4964. @example
  4965. char *foo = NULL;
  4966. c = *foo;    /* @r{This causes a signal and terminates.}  */
  4967. @end example
  4968.  
  4969. @noindent
  4970. Likewise a pointer that has the wrong alignment for the target data type
  4971. (on most types of computer), or points to a part of memory that has
  4972. not been allocated in the process's address space.
  4973.  
  4974. The signal terminates the program, unless the program has arranged to
  4975. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4976. The GNU C Library Reference Manual}).
  4977.  
  4978. However, the signal might not happen if the dereference is optimized
  4979. away.  In the example above, if you don't subsequently use the value
  4980. of @code{c}, GCC might optimize away the code for @code{*foo}.  You
  4981. can prevent such optimization using the @code{volatile} qualifier, as
  4982. shown here:
  4983.  
  4984. @example
  4985. volatile char *p;
  4986. volatile char c;
  4987. c = *p;
  4988. @end example
  4989.  
  4990. You can use this to test whether @code{p} points to unallocated
  4991. memory.  Set up a signal handler first, so the signal won't terminate
  4992. the program.
  4993.  
  4994. @node Void Pointers
  4995. @section Void Pointers
  4996. @cindex void pointers
  4997. @cindex pointers, void
  4998.  
  4999. The peculiar type @code{void *}, a pointer whose target type is
  5000. @code{void}, is used often in C@.  It represents a pointer to
  5001. we-don't-say-what.  Thus,
  5002.  
  5003. @example
  5004. void *numbered_slot_pointer (int);
  5005. @end example
  5006.  
  5007. @noindent
  5008. declares a function @code{numbered_slot_pointer} that takes an
  5009. integer parameter and returns a pointer, but we don't say what type of
  5010. data it points to.
  5011.  
  5012. With type @code{void *}, you can pass the pointer around and test
  5013. whether it is null.  However, dereferencing it gives a @code{void}
  5014. value that can't be used (@pxref{The Void Type}).  To dereference the
  5015. pointer, first convert it to some other pointer type.
  5016.  
  5017. Assignments convert @code{void *} automatically to any other pointer
  5018. type, if the left operand has a pointer type; for instance,
  5019.  
  5020. @example
  5021. @{
  5022.  int *p;
  5023.  /* @r{Converts return value to @code{int *}.}  */
  5024.  p = numbered_slot_pointer (5);
  5025.  @r{@dots{}}
  5026. @}
  5027. @end example
  5028.  
  5029. Passing an argument of type @code{void *} for a parameter that has a
  5030. pointer type also converts.  For example, supposing the function
  5031. @code{hack} is declared to require type @code{float *} for its
  5032. argument, this will convert the null pointer to that type.
  5033.  
  5034. @example
  5035. /* @r{Declare @code{hack} that way.}
  5036.   @r{We assume it is defined somewhere else.}  */
  5037. void hack (float *);
  5038. @dots{}
  5039. /* @r{Now call @code{hack}.}  */
  5040. @{
  5041.  /* @r{Converts return value of @code{numbered_slot_pointer}}
  5042.     @r{to @code{float *} to pass it to @code{hack}.}  */
  5043.  hack (numbered_slot_pointer (5));
  5044.  @r{@dots{}}
  5045. @}
  5046. @end example
  5047.  
  5048.  You can also convert to another pointer type with an explicit cast
  5049. (@pxref{Explicit Type Conversion}), like this:
  5050. @example
  5051. (int *) numbered_slot_pointer (5)
  5052. @end example
  5053.  
  5054. Here is an example which decides at run time which pointer
  5055. type to convert to:
  5056.  
  5057. @example
  5058. void
  5059. extract_int_or_double (void *ptr, bool its_an_int)
  5060. @{
  5061.  if (its_an_int)
  5062.    handle_an_int (*(int *)ptr);
  5063.  else
  5064.    handle_a_double (*(double *)ptr);
  5065. @}
  5066. @end example
  5067.  
  5068. The expression @code{*(int *)ptr} means to convert @code{ptr}
  5069. to type @code{int *}, then dereference it.
  5070.  
  5071. @node Pointer Comparison
  5072. @section Pointer Comparison
  5073. @cindex pointer comparison
  5074. @cindex comparison, pointer
  5075.  
  5076. Two pointer values are equal if they point to the same location, or if
  5077. they are both null.  You can test for this with @code{==} and
  5078. @code{!=}.  Here's a trivial example:
  5079.  
  5080. @example
  5081. @{
  5082.  int i;
  5083.  int *p, *q;
  5084.  
  5085.  p = &i;
  5086.  q = &i;
  5087.  if (p == q)
  5088.    printf ("This will be printed.\n");
  5089.  if (p != q)
  5090.    printf ("This won't be printed.\n");
  5091. @}
  5092. @end example
  5093.  
  5094. Ordering comparisons such as @code{>} and @code{>=} operate on
  5095. pointers by converting them to unsigned integers.  The C standard says
  5096. the two pointers must point within the same object in memory, but on
  5097. GNU/Linux systems these operations simply compare the numeric values
  5098. of the pointers.
  5099.  
  5100. The pointer values to be compared should in principle have the same type, but
  5101. they are allowed to differ in limited cases.  First of all, if the two
  5102. pointers' target types are nearly compatible (@pxref{Compatible
  5103. Types}), the comparison is allowed.
  5104.  
  5105. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  5106. the other is another pointer type, the comparison operator converts
  5107. the @code{void *} pointer to the other type so as to compare them.
  5108. (In standard C, this is not allowed if the other type is a function
  5109. pointer type, but that works in GNU C@.)
  5110.  
  5111. Comparison operators also allow comparing the integer 0 with a pointer
  5112. value.  Thus works by converting 0 to a null pointer of the same type
  5113. as the other operand.
  5114.  
  5115. @node Pointer Arithmetic
  5116. @section Pointer Arithmetic
  5117. @cindex pointer arithmetic
  5118. @cindex arithmetic, pointer
  5119.  
  5120. Adding an integer (positive or negative) to a pointer is valid in C@.
  5121. It assumes that the pointer points to an element in an array, and
  5122. advances or retracts the pointer across as many array elements as the
  5123. integer specifies.  Here is an example, in which adding a positive
  5124. integer advances the pointer to a later element in the same array.
  5125.  
  5126. @example
  5127. void
  5128. incrementing_pointers ()
  5129. @{
  5130.  int array[5] = @{ 45, 29, 104, -3, 123456 @};
  5131.  int elt0, elt1, elt4;
  5132.  
  5133.  int *p = &array[0];
  5134.  /* @r{Now @code{p} points at element 0.  Fetch it.}  */
  5135.  elt0 = *p;
  5136.  
  5137.  ++p;
  5138.  /* @r{Now @code{p} points at element 1.  Fetch it.}  */
  5139.  elt1 = *p;
  5140.  
  5141.  p += 3;
  5142.  /* @r{Now @code{p} points at element 4 (the last).  Fetch it.}  */
  5143.   elt4 = *p;
  5144.  
  5145.   printf ("elt0 %d  elt1 %d  elt4 %d.\n",
  5146.           elt0, elt1, elt4);
  5147.   /* @r{Prints elt0 45  elt1 29  elt4 123456.}  */
  5148. @}
  5149. @end example
  5150.  
  5151. Here's an example where adding a negative integer retracts the pointer
  5152. to an earlier element in the same array.
  5153.  
  5154. @example
  5155. void
  5156. decrementing_pointers ()
  5157. @{
  5158.  int array[5] = @{ 45, 29, 104, -3, 123456 @};
  5159.  int elt0, elt3, elt4;
  5160.  
  5161.  int *p = &array[4];
  5162.  /* @r{Now @code{p} points at element 4 (the last).  Fetch it.}  */
  5163.  elt4 = *p;
  5164.  
  5165.  --p;
  5166.  /* @r{Now @code{p} points at element 3.  Fetch it.}  */
  5167.  elt3 = *p;
  5168.  
  5169.  p -= 3;
  5170.  /* @r{Now @code{p} points at element 0.  Fetch it.}  */
  5171.   elt0 = *p;
  5172.  
  5173.   printf ("elt0 %d  elt3 %d  elt4 %d.\n",
  5174.           elt0, elt3, elt4);
  5175.   /* @r{Prints elt0 45  elt3 -3  elt4 123456.}  */
  5176. @}
  5177. @end example
  5178.  
  5179. If one pointer value was made by adding an integer to another
  5180. pointer value, it should be possible to subtract the pointer values
  5181. and recover that integer.  That works too in C@.
  5182.  
  5183. @example
  5184. void
  5185. subtract_pointers ()
  5186. @{
  5187.  int array[5] = @{ 45, 29, 104, -3, 123456 @};
  5188.  int *p0, *p3, *p4;
  5189.  
  5190.  int *p = &array[4];
  5191.  /* @r{Now @code{p} points at element 4 (the last).  Save the value.}  */
  5192.  p4 = p;
  5193.  
  5194.  --p;
  5195.  /* @r{Now @code{p} points at element 3.  Save the value.}  */
  5196.  p3 = p;
  5197.  
  5198.  p -= 3;
  5199.  /* @r{Now @code{p} points at element 0.  Save the value.}  */
  5200.   p0 = p;
  5201.  
  5202.   printf ("%d, %d, %d, %d\n",
  5203.           p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  5204.   /* @r{Prints 4, 0, 3, -3.}  */
  5205. @}
  5206. @end example
  5207.  
  5208. The addition operation does not know where arrays are.  All it does is
  5209. add the integer (multiplied by object size) to the value of the
  5210. pointer.  When the initial pointer and the result point into a single
  5211. array, the result is well-defined.
  5212.  
  5213. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  5214. into different memory objects.
  5215.  
  5216. The difference between two pointers has type @code{int}, or
  5217. @code{long} if necessary (@pxref{Integer Types}).  The clean way to
  5218. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  5219. file @file{stddef.h}.
  5220.  
  5221. This definition of pointer subtraction is consistent with
  5222. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  5223. @code{p3}, as in ordinary algebra.
  5224.  
  5225. In standard C, addition and subtraction are not allowed on @code{void
  5226. *}, since the target type's size is not defined in that case.
  5227. Likewise, they are not allowed on pointers to function types.
  5228. However, these operations work in GNU C, and the ``size of the target
  5229. type'' is taken as 1.
  5230.  
  5231. @node Pointers and Arrays
  5232. @section Pointers and Arrays
  5233. @cindex pointers and arrays
  5234. @cindex arrays and pointers
  5235.  
  5236. The clean way to refer to an array element is
  5237. @code{@var{array}[@var{index}]}.  Another, complicated way to do the
  5238. same job is to get the address of that element as a pointer, then
  5239. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  5240. equivalently @code{* (@var{array} + @var{index})}).  This first gets a
  5241. pointer to element zero, then increments it with @code{+} to point to
  5242. the desired element, then gets the value from there.
  5243.  
  5244. That pointer-arithmetic construct is the @emph{definition} of square
  5245. brackets in C@.  @code{@var{a}[@var{b}]} means, by definition,
  5246. @code{*(@var{a} + @var{b})}.  This definition uses @var{a} and @var{b}
  5247. symmetrically, so one must be a pointer and the other an integer; it
  5248. does not matter which comes first.
  5249.  
  5250. Since indexing with square brackets is defined in terms of addition
  5251. and dereference, that too is symmetrical.  Thus, you can write
  5252. @code{3[array]} and it is equivalent to @code{array[3]}.  However, it
  5253. would be foolish to write @code{3[array]}, since it has no advantage
  5254. and could confuse people who read the code.
  5255.  
  5256. It may seem like a discrepancy that the definition @code{*(@var{a} +
  5257. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  5258. instead.  Why is this valid?  The name of the array, when used by
  5259. itself as an expression (other than in @code{sizeof}), stands for a
  5260. pointer to the arrays's zeroth element.  Thus, @code{array + 3}
  5261. converts @code{array} implicitly to @code{&array[0]}, and the result
  5262. is a pointer to element 3, equivalent to @code{&array[3]}.
  5263.  
  5264. Since square brackets are defined in terms of such addition,
  5265. @code{array[3]} first converts @code{array} to a pointer.  That's why
  5266. it works to use an array directly in that construct.
  5267.  
  5268. @node Pointer Arithmetic Low Level
  5269. @section Pointer Arithmetic at Low Level
  5270. @cindex pointer arithmetic, low level
  5271. @cindex low level pointer arithmetic
  5272.  
  5273. The behavior of pointer arithmetic is theoretically defined only when
  5274. the pointer values all point within one object allocated in memory.
  5275. But the addition and subtraction operators can't tell whether the
  5276. pointer values are all within one object.  They don't know where
  5277. objects start and end.  So what do they really do?
  5278.  
  5279. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  5280. address, which is in fact an integer---call it @var{pint}.  It treats
  5281. @var{i} as a number of elements of the type that @var{p} points to.
  5282. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  5283. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  5284. (*@var{p})}.  This value is reinterpreted as a pointer like @var{p}.
  5285.  
  5286. If the starting pointer value @var{p} and the result do not point at
  5287. parts of the same object, the operation is not officially legitimate,
  5288. and C code is not ``supposed'' to do it.  But you can do it anyway,
  5289. and it gives precisely the results described by the procedure above.
  5290. In some special situations it can do something useful, but non-wizards
  5291. should avoid it.
  5292.  
  5293. Here's a function to offset a pointer value @emph{as if} it pointed to
  5294. an object of any given size, by explicitly performing that calculation:
  5295.  
  5296. @example
  5297. #include <stdint.h>
  5298.  
  5299. void *
  5300. ptr_add (void *p, int i, int objsize)
  5301. @{
  5302.  intptr_t p_address = (long) p;
  5303.  intptr_t totalsize = i * objsize;
  5304.  intptr_t new_address = p_address + totalsize;
  5305.  return (void *) new_address;
  5306. @}
  5307. @end example
  5308.  
  5309. @noindent
  5310. @cindex @code{intptr_t}
  5311. This does the same job as @code{@var{p} + @var{i}} with the proper
  5312. pointer type for @var{p}.  It uses the type @code{intptr_t}, which is
  5313. defined in the header file @file{stdint.h}.  (In practice, @code{long
  5314. long} would always work, but it is cleaner to use @code{intptr_t}.)
  5315.  
  5316. @node Pointer Increment/Decrement
  5317. @section Pointer Increment and Decrement
  5318. @cindex pointer increment and decrement
  5319. @cindex incrementing pointers
  5320. @cindex decrementing pointers
  5321.  
  5322. The @samp{++} operator adds 1 to a variable.  We have seen it for
  5323. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  5324. For instance, suppose we have a series of positive integers,
  5325. terminated by a zero, and we want to add them all up.
  5326.  
  5327. @example
  5328. int
  5329. sum_array_till_0 (int *p)
  5330. @{
  5331.  int sum = 0;
  5332.  
  5333.  for (;;)
  5334.    @{
  5335.      /* @r{Fetch the next integer.}  */
  5336.      int next = *p++;
  5337.      /* @r{Exit the loop if it's 0.}  */
  5338.      if (next == 0)
  5339.        break;
  5340.      /* @r{Add it into running total.}  */
  5341.      sum += next;
  5342.    @}
  5343.  
  5344.  return sum;
  5345. @}
  5346. @end example
  5347.  
  5348. @noindent
  5349. The statement @samp{break;} will be explained further on (@pxref{break
  5350. Statement}).  Used in this way, it immediately exits the surrounding
  5351. @code{for} statement.
  5352.  
  5353. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  5354. takes precedence over a prefix operator.  Therefore, it dereferences
  5355. @code{p}, and increments @code{p} afterwards.  Incrementing a variable
  5356. means adding 1 to it, as in @code{p = p + 1}.  Since @code{p} is a
  5357. pointer, adding 1 to it advances it by the width of the datum it
  5358. points to---in this case, one @code{int}.  Therefore, each iteration
  5359. of the loop picks up the next integer from the series and puts it into
  5360. @code{next}.
  5361.  
  5362. This @code{for}-loop has no initialization expression since @code{p}
  5363. and @code{sum} are already initialized, it has no end-test since the
  5364. @samp{break;} statement will exit it, and needs no expression to
  5365. advance it since that's done within the loop by incrementing @code{p}
  5366. and @code{sum}.  Thus, those three expressions after @code{for} are
  5367. left empty.
  5368.  
  5369. Another way to write this function is by keeping the parameter value unchanged
  5370. and using indexing to access the integers in the table.
  5371.  
  5372. @example
  5373. int
  5374. sum_array_till_0_indexing (int *p)
  5375. @{
  5376.  int i;
  5377.  int sum = 0;
  5378.  
  5379.  for (i = 0; ; i++)
  5380.    @{
  5381.      /* @r{Fetch the next integer.}  */
  5382.      int next = p[i];
  5383.      /* @r{Exit the loop if it's 0.}  */
  5384.      if (next == 0)
  5385.        break;
  5386.      /* @r{Add it into running total.}  */
  5387.      sum += next;
  5388.    @}
  5389.  
  5390.  return sum;
  5391. @}
  5392. @end example
  5393.  
  5394. In this program, instead of advancing @code{p}, we advance @code{i}
  5395. and add it to @code{p}.  (Recall that @code{p[i]} means @code{*(p +
  5396. i)}.)  Either way, it uses the same address to get the next integer.
  5397.  
  5398. It makes no difference in this program whether we write @code{i++} or
  5399. @code{++i}, because the value is not used.  All that matters is the
  5400. effect, to increment @code{i}.
  5401.  
  5402. The @samp{--} operator also works on pointers; it can be used
  5403. to scan backwards through an array, like this:
  5404.  
  5405. @example
  5406. int
  5407. after_last_nonzero (int *p, int len)
  5408. @{
  5409.  /* @r{Set up @code{q} to point just after the last array element.}  */
  5410.  int *q = p + len;
  5411.  
  5412.  while (q != p)
  5413.    /* @r{Step @code{q} back until it reaches a nonzero element.}  */
  5414.    if (*--q != 0)
  5415.      /* @r{Return the index of the element after that nonzero.}  */
  5416.      return q - p + 1;
  5417.  
  5418.  return 0;
  5419. @}
  5420. @end example
  5421.  
  5422. That function returns the length of the nonzero part of the
  5423. array specified by its arguments; that is, the index of the
  5424. first zero of the run of zeros at the end.
  5425.  
  5426. @node Pointer Arithmetic Drawbacks
  5427. @section Drawbacks of Pointer Arithmetic
  5428. @cindex drawbacks of pointer arithmetic
  5429. @cindex pointer arithmetic, drawbacks
  5430.  
  5431. Pointer arithmetic is clean and elegant, but it is also the cause of a
  5432. major security flaw in the C language.  Theoretically, it is only
  5433. valid to adjust a pointer within one object allocated as a unit in
  5434. memory.  However, if you unintentionally adjust a pointer across the
  5435. bounds of the object and into some other object, the system has no way
  5436. to detect this error.
  5437.  
  5438. A bug which does that can easily result in clobbering part of another
  5439. object.  For example, with @code{array[-1]} you can read or write the
  5440. nonexistent element before the beginning of an array---probably part
  5441. of some other data.
  5442.  
  5443. Combining pointer arithmetic with casts between pointer types, you can
  5444. create a pointer that fails to be properly aligned for its type.  For
  5445. example,
  5446.  
  5447. @example
  5448. int a[2];
  5449. char *pa = (char *)a;
  5450. int *p = (int *)(pa + 1);
  5451. @end example
  5452.  
  5453. @noindent
  5454. gives @code{p} a value pointing to an ``integer'' that includes part
  5455. of @code{a[0]} and part of @code{a[1]}.  Dereferencing that with
  5456. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  5457. contents of that badly aligned @code{int} (@pxref{Signals}.  If it
  5458. ``works,'' it may be quite slow.  It can also cause aliasing
  5459. confusions (@pxref{Aliasing}).
  5460.  
  5461. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  5462. unless it is really necessary.
  5463.  
  5464. @node Pointer-Integer Conversion
  5465. @section Pointer-Integer Conversion
  5466. @cindex pointer-integer conversion
  5467. @cindex conversion between pointers and integers
  5468. @cindex @code{uintptr_t}
  5469.  
  5470. On modern computers, an address is simply a number.  It occupies the
  5471. same space as some size of integer.  In C, you can convert a pointer
  5472. to the appropriate integer types and vice versa, without losing
  5473. information.  The appropriate integer types are @code{uintptr_t} (an
  5474. unsigned type) and @code{intptr_t} (a signed type).  Both are defined
  5475. in @file{stdint.h}.
  5476.  
  5477. For instance,
  5478.  
  5479. @example
  5480. #include <stdint.h>
  5481. #include <stdio.h>
  5482.  
  5483. void
  5484. print_pointer (void *ptr)
  5485. @{
  5486.   uintptr_t converted = (uintptr_t) ptr;
  5487.  
  5488.   printf ("Pointer value is 0x%x\n",
  5489.           (unsigned int) converted);
  5490. @}
  5491. @end example
  5492.  
  5493. @noindent
  5494. The specification @samp{%x} in the template (the first argument) for
  5495. @code{printf} means to represent this argument using hexadecimal
  5496. notation.  It's cleaner to use @code{uintptr_t}, since hexadecimal
  5497. printing treats the number as unsigned, but it won't actually matter:
  5498. all @code{printf} gets to see is the series of bits in the number.
  5499.  
  5500. @strong{Warning:} Converting pointers to integers is risky---don't do
  5501. it unless it is really necessary.
  5502.  
  5503. @node Printing Pointers
  5504. @section Printing Pointers
  5505.  
  5506. To print the numeric value of a pointer, use the @samp{%p} specifier.
  5507. For example:
  5508.  
  5509. @example
  5510. void
  5511. print_pointer (void *ptr)
  5512. @{
  5513.   printf ("Pointer value is %p\n", ptr);
  5514. @}
  5515. @end example
  5516.  
  5517. The specification @samp{%p} works with any pointer type.  It prints
  5518. @samp{0x} followed by the address in hexadecimal, printed as the
  5519. appropriate unsigned integer type.
  5520.  
  5521. @node Structures
  5522. @chapter Structures
  5523. @cindex structures
  5524. @findex struct
  5525. @cindex fields in structures
  5526.  
  5527. A @dfn{structure} is a user-defined data type that holds various
  5528. @dfn{fields} of data.  Each field has a name and a data type specified
  5529. in the structure's definition.
  5530.  
  5531. Here we define a structure suitable for storing a linked list of
  5532. integers.  Each list item will hold one integer, plus a pointer
  5533. to the next item.
  5534.  
  5535. @example
  5536. struct intlistlink
  5537.  @{
  5538.    int datum;
  5539.    struct intlistlink *next;
  5540.  @};
  5541. @end example
  5542.  
  5543. The structure definition has a @dfn{type tag} so that the code can
  5544. refer to this structure.  The type tag here is @code{intlistlink}.
  5545. The definition refers recursively to the same structure through that
  5546. tag.
  5547.  
  5548. You can define a structure without a type tag, but then you can't
  5549. refer to it again.  That is useful only in some special contexts, such
  5550. as inside a @code{typedef} or a @code{union}.
  5551.  
  5552. The contents of the structure are specified by the @dfn{field
  5553. declarations} inside the braces.  Each field in the structure needs a
  5554. declaration there.  The fields in one structure definition must have
  5555. distinct names, but these names do not conflict with any other names
  5556. in the program.
  5557.  
  5558. A field declaration looks just like a variable declaration.  You can
  5559. combine field declarations with the same beginning, just as you can
  5560. combine variable declarations.
  5561.  
  5562. This structure has two fields.  One, named @code{datum}, has type
  5563. @code{int} and will hold one integer in the list.  The other, named
  5564. @code{next}, is a pointer to another @code{struct intlistlink}
  5565. which would be the rest of the list.  In the last list item, it would
  5566. be @code{NULL}.
  5567.  
  5568. This structure definition is recursive, since the type of the
  5569. @code{next} field refers to the structure type.  Such recursion is not
  5570. a problem; in fact, you can use the type @code{struct intlistlink *}
  5571. before the definition of the type @code{struct intlistlink} itself.
  5572. That works because pointers to all kinds of structures really look the
  5573. same at the machine level.
  5574.  
  5575. After defining the structure, you can declare a variable of type
  5576. @code{struct intlistlink} like this:
  5577.  
  5578. @example
  5579. struct intlistlink foo;
  5580. @end example
  5581.  
  5582. The structure definition itself can serve as the beginning of a
  5583. variable declaration, so you can declare variables immediately after,
  5584. like this:
  5585.  
  5586. @example
  5587. struct intlistlink
  5588.  @{
  5589.    int datum;
  5590.    struct intlistlink *next;
  5591.  @} foo;
  5592. @end example
  5593.  
  5594. @noindent
  5595. But that is ugly.  It is almost always clearer to separate the
  5596. definition of the structure from its uses.
  5597.  
  5598. Declaring a structure type inside a block (@pxref{Blocks}) limits
  5599. the scope of the structure type name to that block.  That means the
  5600. structure type is recognized only within that block.  Declaring it in
  5601. a function parameter list, as here,
  5602.  
  5603. @example
  5604. int f (struct foo @{int a, b@} parm);
  5605. @end example
  5606.  
  5607. @noindent
  5608. (assuming that @code{struct foo} is not already defined) limits the
  5609. scope of the structure type @code{struct foo} to that parameter list;
  5610. that is basically useless, so it triggers a warning.
  5611.  
  5612. Standard C requires at least one field in a structure.
  5613. GNU C does not require this.
  5614.  
  5615. @menu
  5616. * Referencing Fields::           Accessing field values in a structure object.
  5617. * Dynamic Memory Allocation::    Allocating space for objects
  5618.                                   while the program is running.
  5619. * Field Offset::                 Memory layout of fields within a structure.
  5620. * Structure Layout::             Planning the memory layout of fields.
  5621. * Packed Structures::            Packing structure fields as close as possible.
  5622. * Bit Fields::                   Dividing integer fields
  5623.                                   into fields with fewer bits.
  5624. * Bit Field Packing::            How bit fields pack together in integers.
  5625. * const Fields::                 Making structure fields immutable.
  5626. * Zero Length::                  Zero-length array as a variable-length object.
  5627. * Flexible Array Fields::        Another approach to variable-length objects.
  5628. * Overlaying Structures::        Casting one structure type
  5629.                                   over an object of another structure type.
  5630. * Structure Assignment::         Assigning values to structure objects.
  5631. * Unions::                       Viewing the same object in different types.
  5632. * Packing With Unions::          Using a union type to pack various types into
  5633.                                   the same memory space.
  5634. * Cast to Union::                Casting a value one of the union's alternative
  5635.                                   types to the type of the union itself.
  5636. * Structure Constructors::       Building new structure objects.
  5637. * Unnamed Types as Fields::      Fields' types do not always need names.
  5638. * Incomplete Types::             Types which have not been fully defined.
  5639. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  5640. * Type Tags::                    Scope of structure and union type tags.
  5641. @end menu
  5642.  
  5643. @node Referencing Fields
  5644. @section Referencing Structure Fields
  5645. @cindex referencing structure fields
  5646. @cindex structure fields, referencing
  5647.  
  5648. To make a structure useful, there has to be a way to examine and store
  5649. its fields.  The @samp{.} (period) operator does that; its use looks
  5650. like @code{@var{object}.@var{field}}.
  5651.  
  5652. Given this structure and variable,
  5653.  
  5654. @example
  5655. struct intlistlink
  5656.  @{
  5657.    int datum;
  5658.    struct intlistlink *next;
  5659.  @};
  5660.  
  5661. struct intlistlink foo;
  5662. @end example
  5663.  
  5664. @noindent
  5665. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  5666. fields in the value of @code{foo}.  These fields are lvalues, so you
  5667. can store values into them, and read the values out again.
  5668.  
  5669. Most often, structures are dynamically allocated (see the next
  5670. section), and we refer to the objects via pointers.
  5671. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  5672. abbreviation: @code{p->@var{field}}.  For instance, assume the program
  5673. contains this declaration:
  5674.  
  5675. @example
  5676. struct intlistlink *ptr;
  5677. @end example
  5678.  
  5679. @noindent
  5680. You can write @code{ptr->datum} and @code{ptr->next} to refer
  5681. to the two fields in the object that @code{ptr} points to.
  5682.  
  5683. If a unary operator precedes an expression using @samp{->},
  5684. the @samp{->} nests inside:
  5685.  
  5686. @example
  5687.  -ptr->datum   @r{is equivalent to}   -(ptr->datum)
  5688. @end example
  5689.  
  5690. You can intermix @samp{->} and @samp{.} without parentheses,
  5691. as shown here:
  5692.  
  5693. @example
  5694. struct @{ double d; struct intlistlink l; @} foo;
  5695.  
  5696. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  5697. @end example
  5698.  
  5699. @node Dynamic Memory Allocation
  5700. @section Dynamic Memory Allocation
  5701. @cindex dynamic memory allocation
  5702. @cindex memory allocation, dynamic
  5703. @cindex allocating memory dynamically
  5704.  
  5705. To allocate an object dynamically, call the library function
  5706. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  5707. Reference Manual}).  Here is how to allocate an object of type
  5708. @code{struct intlistlink}.  To make this code work, include the file
  5709. @file{stdlib.h}, like this:
  5710.  
  5711. @example
  5712. #include <stddef.h>  /* @r{Defines @code{NULL}.} */
  5713. #include <stdlib.h>  /* @r{Declares @code{malloc}.}  */
  5714.  
  5715. @dots{}
  5716.  
  5717. struct intlistlink *
  5718. alloc_intlistlink ()
  5719. @{
  5720.  struct intlistlink *p;
  5721.  
  5722.  p = malloc (sizeof (struct intlistlink));
  5723.  
  5724.  if (p == NULL)
  5725.    fatal ("Ran out of storage");
  5726.  
  5727.  /* @r{Initialize the contents.} */
  5728.  p->datum = 0;
  5729.  p->next = NULL;
  5730.  
  5731.  return p;
  5732. @}
  5733. @end example
  5734.  
  5735. @noindent
  5736. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  5737. will automatically convert it to type @code{struct intlistlink *}.
  5738. The return value of @code{malloc} is always sufficiently aligned
  5739. (@pxref{Type Alignment}) that it is valid for any data type.
  5740.  
  5741. The test for @code{p == NULL} is necessary because @code{malloc}
  5742. returns a null pointer if it cannot get any storage.  We assume that
  5743. the program defines the function @code{fatal} to report a fatal error
  5744. to the user.
  5745.  
  5746. Here's how to add one more integer to the front of such a list:
  5747.  
  5748. @example
  5749. struct intlistlink *my_list = NULL;
  5750.  
  5751. void
  5752. add_to_mylist (int my_int)
  5753. @{
  5754.  struct intlistlink *p = alloc_intlistlink ();
  5755.  
  5756.  p->datum = my_int;
  5757.  p->next = mylist;
  5758.  mylist = p;
  5759. @}
  5760. @end example
  5761.  
  5762. The way to free the objects is by calling @code{free}.  Here's
  5763. a function to free all the links in one of these lists:
  5764.  
  5765. @example
  5766. void
  5767. free_intlist (struct intlistlink *p)
  5768. @{
  5769.  while (p)
  5770.    @{
  5771.      struct intlistlink *q = p;
  5772.      p = p->next;
  5773.      free (q);
  5774.    @}
  5775. @}
  5776. @end example
  5777.  
  5778. We must extract the @code{next} pointer from the object before freeing
  5779. it, because @code{free} can clobber the data that was in the object.
  5780. For the same reason, the program must not use the list any more after
  5781. freeing its elements.  To make sure it won't, it is best to clear out
  5782. the variable where the list was stored, like this:
  5783.  
  5784. @example
  5785. free_intlist (mylist);
  5786.  
  5787. mylist = NULL;
  5788. @end example
  5789.  
  5790. @node Field Offset
  5791. @section Field Offset
  5792. @cindex field offset
  5793. @cindex structure field offset
  5794. @cindex offset of structure fields
  5795.  
  5796. To determine the offset of a given field @var{field} in a structure
  5797. type @var{type}, use the macro @code{offsetof}, which is defined in
  5798. the file @file{stddef.h}.  It is used like this:
  5799.  
  5800. @example
  5801. offsetof (@var{type}, @var{field})
  5802. @end example
  5803.  
  5804. Here is an example:
  5805.  
  5806. @example
  5807. struct foo
  5808. @{
  5809.  int element;
  5810.  struct foo *next;
  5811. @};
  5812.  
  5813. offsetof (struct foo, next)
  5814. /* @r{On most machines that is 4.  It may be 8.}  */
  5815. @end example
  5816.  
  5817. @node Structure Layout
  5818. @section Structure Layout
  5819. @cindex structure layout
  5820. @cindex layout of structures
  5821.  
  5822. The rest of this chapter covers advanced topics about structures.  If
  5823. you are just learning C, you can skip it.
  5824.  
  5825. The precise layout of a @code{struct} type is crucial when using it to
  5826. overlay hardware registers, to access data structures in shared
  5827. memory, or to assemble and disassemble packets for network
  5828. communication.  It is also important for avoiding memory waste when
  5829. the program makes many objects of that type.  However, the layout
  5830. depends on the target platform.  Each platform has conventions for
  5831. structure layout, which compilers need to follow.
  5832.  
  5833. Here are the conventions used on most platforms.
  5834.  
  5835. The structure's fields appear in the structure layout in the order
  5836. they are declared.  When possible, consecutive fields occupy
  5837. consecutive bytes within the structure.  However, if a field's type
  5838. demands more alignment than it would get that way, C gives it the
  5839. alignment it requires by leaving a gap after the previous field.
  5840.  
  5841. Once all the fields have been laid out, it is possible to determine
  5842. the structure's alignment and size.  The structure's alignment is the
  5843. maximum alignment of any of the fields in it.  Then the structure's
  5844. size is rounded up to a multiple of its alignment.  That may require
  5845. leaving a gap at the end of the structure.
  5846.  
  5847. Here are some examples, where we assume that @code{char} has size and
  5848. alignment 1 (always true), and @code{int} has size and alignment 4
  5849. (true on most kinds of computers):
  5850.  
  5851. @example
  5852. struct foo
  5853. @{
  5854.  char a, b;
  5855.  int c;
  5856. @};
  5857. @end example
  5858.  
  5859. @noindent
  5860. This structure occupies 8 bytes, with an alignment of 4.  @code{a} is
  5861. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  5862. There is a gap of 2 bytes before @code{c}.
  5863.  
  5864. Contrast that with this structure:
  5865.  
  5866. @example
  5867. struct foo
  5868. @{
  5869.  char a;
  5870.  int c;
  5871.  char b;
  5872. @};
  5873. @end example
  5874.  
  5875. This structure has size 12 and alignment 4.  @code{a} is at offset 0,
  5876. @code{c} is at offset 4, and @code{b} is at offset 8.  There are two
  5877. gaps: three bytes before @code{c}, and three bytes at the end.
  5878.  
  5879. These two structures have the same contents at the C level, but one
  5880. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  5881. fields.  A reliable way to avoid this sort of wastage is to order the
  5882. fields by size, biggest fields first.
  5883.  
  5884. @node Packed Structures
  5885. @section Packed Structures
  5886. @cindex packed structures
  5887. @cindex @code{__attribute__((packed))}
  5888.  
  5889. In GNU C you can force a structure to be laid out with no gaps by
  5890. adding @code{__attribute__((packed))} after @code{struct} (or at the
  5891. end of the structure type declaration).  Here's an example:
  5892.  
  5893. @example
  5894. struct __attribute__((packed)) foo
  5895. @{
  5896.  char a;
  5897.  int c;
  5898.  char b;
  5899. @};
  5900. @end example
  5901.  
  5902. Without @code{__attribute__((packed))}, this structure occupies 12
  5903. bytes (as described in the previous section), assuming 4-byte
  5904. alignment for @code{int}.  With @code{__attribute__((packed))}, it is
  5905. only 6 bytes long---the sum of the lengths of its fields.
  5906.  
  5907. Use of @code{__attribute__((packed))} often results in fields that
  5908. don't have the normal alignment for their types.  Taking the address
  5909. of such a field can result in an invalid pointer because of its
  5910. improper alignment.  Dereferencing such a pointer can cause a
  5911. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  5912. unaligned pointers.
  5913.  
  5914. @xref{Attributes}.
  5915.  
  5916. @node Bit Fields
  5917. @section Bit Fields
  5918. @cindex bit fields
  5919.  
  5920. A structure field declaration with an integer type can specify the
  5921. number of bits the field should occupy.  We call that a @dfn{bit
  5922. field}.  These are useful because consecutive bit fields are packed
  5923. into a larger storage unit.  For instance,
  5924.  
  5925. @example
  5926. unsigned char opcode: 4;
  5927. @end example
  5928.  
  5929. @noindent
  5930. specifies that this field takes just 4 bits.
  5931. Since it is unsigned, its possible values range
  5932. from 0 to 15.  A signed field with 4 bits, such as this,
  5933.  
  5934. @example
  5935. signed char small: 4;
  5936. @end example
  5937.  
  5938. @noindent
  5939. can hold values from -8 to 7.
  5940.  
  5941. You can subdivide a single byte into those two parts by writing
  5942.  
  5943. @example
  5944. unsigned char opcode: 4;
  5945. signed char small: 4;
  5946. @end example
  5947.  
  5948. @noindent
  5949. in the structure.  With bit fields, these two numbers fit into
  5950. a single @code{char}.
  5951.  
  5952. Here's how to declare a one-bit field that can hold either 0 or 1:
  5953.  
  5954. @example
  5955. unsigned char special_flag: 1;
  5956. @end example
  5957.  
  5958. You can also use the @code{bool} type for bit fields:
  5959.  
  5960. @example
  5961. bool special_flag: 1;
  5962. @end example
  5963.  
  5964. Except when using @code{bool} (which is always unsigned,
  5965. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  5966. for a bit field.  There is a default, if that's not specified: the bit
  5967. field is signed if plain @code{char} is signed, except that the option
  5968. @option{-funsigned-bitfields} forces unsigned as the default.  But it
  5969. is cleaner not to depend on this default.
  5970.  
  5971. Bit fields are special in that you cannot take their address with
  5972. @samp{&}.  They are not stored with the size and alignment appropriate
  5973. for the specified type, so they cannot be addressed through pointers
  5974. to that type.
  5975.  
  5976. @node Bit Field Packing
  5977. @section Bit Field Packing
  5978.  
  5979. Programs to communicate with low-level hardware interfaces need to
  5980. define bit fields laid out to match the hardware data.  This section
  5981. explains how to do that.
  5982.  
  5983. Consecutive bit fields are packed together, but each bit field must
  5984. fit within a single object of its specified type.  In this example,
  5985.  
  5986. @example
  5987. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  5988. @end example
  5989.  
  5990. @noindent
  5991. all five fields fit consecutively into one two-byte @code{short}.
  5992. They need 15 bits, and one @code{short} provides 16.  By contrast,
  5993.  
  5994. @example
  5995. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  5996. @end example
  5997.  
  5998. @noindent
  5999. needs three bytes.  It fits @code{a} and @code{b} into one
  6000. @code{char}, but @code{c} won't fit in that @code{char} (they would
  6001. add up to 9 bits).  So @code{c} and @code{d} go into a second
  6002. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  6003. Then @code{e} needs a third @code{char}.  By contrast,
  6004.  
  6005. @example
  6006. unsigned char a : 3, b : 3;
  6007. unsigned int c : 3;
  6008. unsigned char d : 3, e : 3;
  6009. @end example
  6010.  
  6011. @noindent
  6012. needs only two bytes: the type @code{unsigned int}
  6013. allows @code{c} to straddle bytes that are in the same word.
  6014.  
  6015. You can leave a gap of a specified number of bits by defining a
  6016. nameless bit field.  This looks like @code{@var{type} : @var{nbits};}.
  6017. It is allocated space in the structure just as a named bit field would
  6018. be allocated.
  6019.  
  6020. You can force the following bit field to advance to the following
  6021. aligned memory object with @code{@var{type} : 0;}.
  6022.  
  6023. Both of these constructs can syntactically share @var{type} with
  6024. ordinary bit fields.  This example illustrates both:
  6025.  
  6026. @example
  6027. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  6028. @end example
  6029.  
  6030. @noindent
  6031. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  6032. between them.  Then @code{: 0} advances to the next @code{int},
  6033. so @code{c} and @code{d} fit into that one.
  6034.  
  6035. These rules for packing bit fields apply to most target platforms,
  6036. including all the usual real computers.  A few embedded controllers
  6037. have special layout rules.
  6038.  
  6039. @node const Fields
  6040. @section @code{const} Fields
  6041. @cindex const fields
  6042. @cindex structure fields, constant
  6043.  
  6044. @c ??? Is this a C standard feature?
  6045.  
  6046. A structure field declared @code{const} cannot be assigned to
  6047. (@pxref{const}).  For instance, let's define this modified version of
  6048. @code{struct intlistlink}:
  6049.  
  6050. @example
  6051. struct intlistlink_ro  /* @r{``ro'' for read-only.}  */
  6052.  @{
  6053.    const int datum;
  6054.    struct intlistlink *next;
  6055.  @};
  6056. @end example
  6057.  
  6058. This structure can be used to prevent part of the code from modifying
  6059. the @code{datum} field:
  6060.  
  6061. @example
  6062. /* @r{@code{p} has type @code{struct intlistlink *}.}
  6063.   @r{Convert it to @code{struct intlistlink_ro *}.}  */
  6064. struct intlistlink_ro *q
  6065.  = (struct intlistlink_ro *) p;
  6066.  
  6067. q->datum = 5;     /* @r{Error!} */
  6068. p->datum = 5;     /* @r{Valid since @code{*p} is}
  6069.                     @r{not a @code{struct intlistlink_ro}.}  */
  6070. @end example
  6071.  
  6072. A @code{const} field can get a value in two ways: by initialization of
  6073. the whole structure, and by making a pointer-to-structure point to an object
  6074. in which that field already has a value.
  6075.  
  6076. Any @code{const} field in a structure type makes assignment impossible
  6077. for structures of that type (@pxref{Structure Assignment}).  That is
  6078. because structure assignment works by assigning the structure's
  6079. fields, one by one.
  6080.  
  6081. @node Zero Length
  6082. @section Arrays of Length Zero
  6083. @cindex array of length zero
  6084. @cindex zero-length arrays
  6085. @cindex length-zero arrays
  6086.  
  6087. GNU C allows zero-length arrays.  They are useful as the last element
  6088. of a structure that is really a header for a variable-length object.
  6089. Here's an example, where we construct a variable-size structure
  6090. to hold a line which is @code{this_length} characters long:
  6091.  
  6092. @example
  6093. struct line @{
  6094.  int length;
  6095.  char contents[0];
  6096. @};
  6097.  
  6098. struct line *thisline
  6099.  = ((struct line *)
  6100.     malloc (sizeof (struct line)
  6101.             + this_length));
  6102. thisline->length = this_length;
  6103. @end example
  6104.  
  6105. In ISO C90, we would have to give @code{contents} a length of 1, which
  6106. means either wasting space or complicating the argument to @code{malloc}.
  6107.  
  6108. @node Flexible Array Fields
  6109. @section Flexible Array Fields
  6110. @cindex flexible array fields
  6111. @cindex array fields, flexible
  6112.  
  6113. The C99 standard adopted a more complex equivalent of zero-length
  6114. array fields.  It's called a @dfn{flexible array}, and it's indicated
  6115. by omitting the length, like this:
  6116.  
  6117. @example
  6118. struct line
  6119. @{
  6120.  int length;
  6121.  char contents[];
  6122. @};
  6123. @end example
  6124. The flexible array has to be the last field in the structure, and there
  6125. must be other fields before it.
  6126. Under the C standard, a structure with a flexible array can't be part
  6127. of another structure, and can't be an element of an array.
  6128. GNU C allows static initialization of flexible array fields.  The effect
  6129. is to ``make the array long enough'' for the initializer.
  6130. @example
  6131. struct f1 @{ int x; int y[]; @} f1
  6132.  = @{ 1, @{ 2, 3, 4 @} @};
  6133. @end example
  6134. @noindent
  6135. This defines a structure variable named @code{f1}
  6136. whose type is @code{struct f1}.  In C, a variable name or function name
  6137. never conflicts with a structure type tag.
  6138. Omitting the flexible array field's size lets the initializer
  6139. determine it.  This is allowed only when the flexible array is defined
  6140. in the outermost structure and you declare a variable of that
  6141. structure type.  For example:
  6142. @example
  6143. struct foo @{ int x; int y[]; @};
  6144. struct bar @{ struct foo z; @};
  6145. struct foo a = @{ 1, @{ 2, 3, 4 @} @};        // @r{Valid.}
  6146. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @};    // @r{Invalid.}
  6147. struct bar c = @{ @{ 1, @{ @} @} @};            // @r{Valid.}
  6148. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @};  // @r{Invalid.}
  6149. @end example
  6150.  
  6151. @node Overlaying Structures
  6152. @section Overlaying Different Structures
  6153. @cindex overlaying structures
  6154. @cindex structures, overlaying
  6155.  
  6156. Be careful about using different structure types to refer to the same
  6157. memory within one function, because GNU C can optimize code assuming
  6158. it never does that.  @xref{Aliasing}.  Here's an example of the kind of
  6159. aliasing that can cause the problem:
  6160.  
  6161. @example
  6162. struct a @{ int size; char *data; @};
  6163. struct b @{ int size; char *data; @};
  6164. struct a foo;
  6165. struct b *q = (struct b *) &foo;
  6166. @end example
  6167.  
  6168. Here @code{q} points to the same memory that the variable @code{foo}
  6169. occupies, but they have two different types.  The two types
  6170. @code{struct a} and @code{struct b} are defined alike, but they are
  6171. not the same type.  Interspersing references using the two types,
  6172. like this,
  6173.  
  6174. @example
  6175. p->size = 0;
  6176. q->size = 1;
  6177. x = p->size;
  6178. @end example
  6179.  
  6180. @noindent
  6181. allows GNU C to assume that @code{p->size} is still zero when it is
  6182. copied into @code{x}.  The compiler ``knows'' that @code{q} points to
  6183. a @code{struct b} and this cannot overlap with a @code{struct a}.
  6184.  
  6185. Other compilers might also do this optimization.  The ISO C standard
  6186. considers such code erroneous, precisely so that this optimization
  6187. will be valid.
  6188.  
  6189. @node Structure Assignment
  6190. @section Structure Assignment
  6191. @cindex structure assignment
  6192. @cindex assigning structures
  6193.  
  6194. Assignment operating on a structure type copies the structure.  The
  6195. left and right operands must have the same type.  Here is an example:
  6196.  
  6197. @example
  6198. #include <stddef.h>  /* @r{Defines @code{NULL}.} */
  6199. #include <stdlib.h>  /* @r{Declares @code{malloc}.}  */
  6200. @r{@dots{}}
  6201.  
  6202. struct point @{ double x, y; @};
  6203.  
  6204. struct point *
  6205. copy_point (struct point point)
  6206. @{
  6207.  struct point *p
  6208.    = (struct point *) malloc (sizeof (struct point));
  6209.  if (p == NULL)
  6210.    fatal ("Out of memory");
  6211.  *p = point;
  6212.  return p;
  6213. @}
  6214. @end example
  6215.  
  6216. Notionally, assignment on a structure type works by copying each of
  6217. the fields.  Thus, if any of the fields has the @code{const}
  6218. qualifier, that structure type does not allow assignment:
  6219.  
  6220. @example
  6221. struct point @{ const double x, y; @};
  6222.  
  6223. struct point a, b;
  6224.  
  6225. a = b;            /* @r{Error!} */
  6226. @end example
  6227.  
  6228. @xref{Assignment Expressions}.
  6229.  
  6230. @node Unions
  6231. @section Unions
  6232. @cindex unions
  6233. @findex union
  6234.  
  6235. A @dfn{union type} defines alternative ways of looking at the same
  6236. piece of memory.  Each alternative view is defined with a data type,
  6237. and identified by a name.  A union definition looks like this:
  6238.  
  6239. @example
  6240. union @var{name}
  6241. @{
  6242.  @var{alternative declarations}@r{@dots{}}
  6243. @};
  6244. @end example
  6245.  
  6246. Each alternative declaration looks like a structure field declaration,
  6247. except that it can't be a bit field.  For instance,
  6248.  
  6249. @example
  6250. union number
  6251. @{
  6252.  long int integer;
  6253.  double float;
  6254. @}
  6255. @end example
  6256.  
  6257. @noindent
  6258. lets you store either an integer (type @code{long int}) or a floating
  6259. point number (type @code{double}) in the same place in memory.  The
  6260. length and alignment of the union type are the maximum of all the
  6261. alternatives---they do not have to be the same.  In this union
  6262. example, @code{double} probably takes more space than @code{long int},
  6263. but that doesn't cause a problem in programs that use the union in the
  6264. normal way.
  6265.  
  6266. The members don't have to be different in data type.  Sometimes
  6267. each member pertains to a way the data will be used.  For instance,
  6268.  
  6269. @example
  6270. union datum
  6271. @{
  6272.  double latitude;
  6273.  double longitude;
  6274.  double height;
  6275.  double weight;
  6276.  int continent;
  6277. @}
  6278. @end example
  6279.  
  6280. This union holds one of several kinds of data; most kinds are floating
  6281. points, but the value can also be a code for a continent which is an
  6282. integer.  You @emph{could} use one member of type @code{double} to
  6283. access all the values which have that type, but the different member
  6284. names will make the program clearer.
  6285.  
  6286. The alignment of a union type is the maximum of the alignments of the
  6287. alternatives.  The size of the union type is the maximum of the sizes
  6288. of the alternatives, rounded up to a multiple of the alignment
  6289. (because every type's size must be a multiple of its alignment).
  6290.  
  6291. All the union alternatives start at the address of the union itself.
  6292. If an alternative is shorter than the union as a whole, it occupies
  6293. the first part of the union's storage, leaving the last part unused
  6294. @emph{for that alternative}.
  6295.  
  6296. @strong{Warning:} if the code stores data using one union alternative
  6297. and accesses it with another, the results depend on the kind of
  6298. computer in use.  Only wizards should try to do this.  However, when
  6299. you need to do this, a union is a clean way to do it.
  6300.  
  6301. Assignment works on any union type by copying the entire value.
  6302.  
  6303. @node Packing With Unions
  6304. @section Packing With Unions
  6305.  
  6306. Sometimes we design a union with the intention of packing various
  6307. kinds of objects into a certain amount of memory space.  For example.
  6308.  
  6309. @example
  6310. union bytes8
  6311. @{
  6312.  long long big_int_elt;
  6313.  double double_elt;
  6314.  struct @{ int first, second; @} two_ints;
  6315.  struct @{ void *first, *second; @} two_ptrs;
  6316. @};
  6317.  
  6318. union bytes8 *p;
  6319. @end example
  6320.  
  6321. This union makes it possible to look at 8 bytes of data that @code{p}
  6322. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  6323. single floating-point number (@code{p->double_elt}), as a pair of
  6324. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  6325. as a pair of pointers (@code{p->two_ptrs.first} and
  6326. @code{p->two_ptrs.second}).
  6327.  
  6328. To pack storage with such a union makes assumptions about the sizes of
  6329. all the types involved.  This particular union was written expecting a
  6330. pointer to have the same size as @code{int}.  On a machine where one
  6331. pointer takes 8 bytes, the code using this union probably won't work
  6332. as expected.  The union, as such, will function correctly---if you
  6333. store two values through @code{two_ints} and extract them through
  6334. @code{two_ints}, you will get the same integers back---but the part of
  6335. the program that expects the union to be 8 bytes long could
  6336. malfunction, or at least use too much space.
  6337.  
  6338. The above example shows one case where a @code{struct} type with no
  6339. tag can be useful.  Another way to get effectively the same result
  6340. is with arrays as members of the union:
  6341.  
  6342. @example
  6343. union eight_bytes
  6344. @{
  6345.  long long big_int_elt;
  6346.  double double_elt;
  6347.  int two_ints[2];
  6348.  void *two_ptrs[2];
  6349. @};
  6350. @end example
  6351.  
  6352. @node Cast to Union
  6353. @section Cast to a Union Type
  6354. @cindex cast to a union
  6355. @cindex union, casting to a
  6356.  
  6357. In GNU C, you can explicitly cast any of the alternative types to the
  6358. union type; for instance,
  6359.  
  6360. @example
  6361. (union eight_bytes) (long long) 5
  6362. @end example
  6363.  
  6364. @noindent
  6365. makes a value of type @code{union eight_bytes} which gets its contents
  6366. through the alternative named @code{big_int_elt}.
  6367.  
  6368. The value being cast must exactly match the type of the alternative,
  6369. so this is not valid:
  6370.  
  6371. @example
  6372. (union eight_bytes) 5  /* @r{Error!  5 is @code{int}.} */
  6373. @end example
  6374.  
  6375. A cast to union type looks like any other cast, except that the type
  6376. specified is a union type.  You can specify the type either with
  6377. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  6378. Typedef Names}).
  6379.  
  6380. Using the cast as the right-hand side of an assignment to a variable of
  6381. union type is equivalent to storing in an alternative of the union:
  6382.  
  6383. @example
  6384. union foo u;
  6385.  
  6386. u = (union foo) x   @r{means}   u.i = x
  6387.  
  6388. u = (union foo) y   @r{means}   u.d = y
  6389. @end example
  6390.  
  6391. You can also use the union cast as a function argument:
  6392.  
  6393. @example
  6394. void hack (union foo);
  6395. @r{@dots{}}
  6396. hack ((union foo) x);
  6397. @end example
  6398.  
  6399. @node Structure Constructors
  6400. @section Structure Constructors
  6401. @cindex structure constructors
  6402. @cindex constructors, structure
  6403.  
  6404. You can construct a structure value by writing its type in
  6405. parentheses, followed by an initializer that would be valid in a
  6406. declaration for that type.  For instance, given this declaration,
  6407.  
  6408. @example
  6409. struct foo @{int a; char b[2];@} structure;
  6410. @end example
  6411.  
  6412. @noindent
  6413. you can create a @code{struct foo} value as follows:
  6414.  
  6415. @example
  6416. ((struct foo) @{x + y, 'a', 0@})
  6417. @end example
  6418.  
  6419. @noindent
  6420. This specifies @code{x + y} for field @code{a},
  6421. the character @samp{a} for field @code{b}'s element 0,
  6422. and the null character for field @code{b}'s element 1.
  6423.  
  6424. The parentheses around that constructor are to necessary, but we
  6425. recommend writing them to make the nesting of the containing
  6426. expression clearer.
  6427.  
  6428. You can also show the nesting of the two by writing it like
  6429. this:
  6430.  
  6431. @example
  6432. ((struct foo) @{x + y, @{'a', 0@} @})
  6433. @end example
  6434.  
  6435. Each of those is equivalent to writing the following statement
  6436. expression (@pxref{Statement Exprs}):
  6437.  
  6438. @example
  6439. (@{
  6440.  struct foo temp = @{x + y, 'a', 0@};
  6441.  temp;
  6442. @})
  6443. @end example
  6444.  
  6445. You can also create a union value this way, but it is not especially
  6446. useful since that is equivalent to doing a cast:
  6447.  
  6448. @example
  6449.  ((union whosis) @{@var{value}@})
  6450. @r{is equivalent to}
  6451.  ((union whosis) (@var{value}))
  6452. @end example
  6453.  
  6454. @node Unnamed Types as Fields
  6455. @section Unnamed Types as Fields
  6456. @cindex unnamed structures
  6457. @cindex unnamed unions
  6458. @cindex structures, unnamed
  6459. @cindex unions, unnamed
  6460.  
  6461. A structure or a union can contain, as fields,
  6462. unnamed structures and unions.  Here's an example:
  6463.  
  6464. @example
  6465. struct
  6466. @{
  6467.  int a;
  6468.  union
  6469.  @{
  6470.    int b;
  6471.    float c;
  6472.  @};
  6473.  int d;
  6474. @} foo;
  6475. @end example
  6476.  
  6477. @noindent
  6478. You can access the fields of the unnamed union within @code{foo} as if they
  6479. were individual fields at the same level as the union definition:
  6480.  
  6481. @example
  6482. foo.a = 42;
  6483. foo.b = 47;
  6484. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  6485. foo.d = 314;
  6486. @end example
  6487.  
  6488. Avoid using field names that could cause ambiguity.  For example, with
  6489. this definition:
  6490.  
  6491. @example
  6492. struct
  6493. @{
  6494.  int a;
  6495.  struct
  6496.  @{
  6497.    int a;
  6498.    float b;
  6499.  @};
  6500. @} foo;
  6501. @end example
  6502.  
  6503. @noindent
  6504. it is impossible to tell what @code{foo.a} refers to.  GNU C reports
  6505. an error when a definition is ambiguous in this way.
  6506.  
  6507. @node Incomplete Types
  6508. @section Incomplete Types
  6509. @cindex incomplete types
  6510. @cindex types, incomplete
  6511.  
  6512. A type that has not been fully defined is called an @dfn{incomplete
  6513. type}.  Structure and union types are incomplete when the code makes a
  6514. forward reference, such as @code{struct foo}, before defining the
  6515. type.  An array type is incomplete when its length is unspecified.
  6516.  
  6517. You can't use an incomplete type to declare a variable or field, or
  6518. use it for a function parameter or return type.  The operators
  6519. @code{sizeof} and @code{_Alignof} give errors when used on an
  6520. incomplete type.
  6521.  
  6522. However, you can define a pointer to an incomplete type, and declare a
  6523. variable or field with such a pointer type.  In general, you can do
  6524. everything with such pointers except dereference them.  For example:
  6525.  
  6526. @example
  6527. extern void bar (struct mysterious_value *);
  6528.  
  6529. void
  6530. foo (struct mysterious_value *arg)
  6531. @{
  6532.  bar (arg);
  6533. @}
  6534.  
  6535. @r{@dots{}}
  6536.  
  6537. @{
  6538.  struct mysterious_value *p, **q;
  6539.  
  6540.  p = *q;
  6541.  foo (p);
  6542. @}
  6543. @end example
  6544.  
  6545. @noindent
  6546. These examples are valid because the code doesn't try to understand
  6547. what @code{p} points to; it just passes the pointer around.
  6548. (Presumably @code{bar} is defined in some other file that really does
  6549. have a definition for @code{struct mysterious_value}.)  However,
  6550. dereferencing the pointer would get an error; that requires a
  6551. definition for the structure type.
  6552.  
  6553. @node Intertwined Incomplete Types
  6554. @section Intertwined Incomplete Types
  6555.  
  6556. When several structure types contain pointers to each other, you can
  6557. define the types in any order because pointers to types that come
  6558. later are incomplete types.  Thus,
  6559. Here is an example.
  6560.  
  6561. @example
  6562. /* @r{An employee record points to a group.}  */
  6563. struct employee
  6564. @{
  6565.  char *name;
  6566.  @r{@dots{}}
  6567.  struct group *group;  /* @r{incomplete type.}  */
  6568.  @r{@dots{}}
  6569. @};
  6570.  
  6571. /* @r{An employee list points to employees.}  */
  6572. struct employee_list
  6573. @{
  6574.  struct employee *this_one;
  6575.  struct employee_list *next;  /* @r{incomplete type.}  */
  6576.  @r{@dots{}}
  6577. @};
  6578.  
  6579. /* @r{A group points to one employee_list.}  */
  6580. struct group
  6581. @{
  6582.  char *name;
  6583.  @r{@dots{}}
  6584.  struct employee_list *employees;
  6585.  @r{@dots{}}
  6586. @};
  6587. @end example
  6588.  
  6589. @node Type Tags
  6590. @section Type Tags
  6591. @cindex type tags
  6592.  
  6593. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  6594. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  6595. a @dfn{type tag}.  In C, a type tag never conflicts with a variable
  6596. name or function name; the type tags have a separate @dfn{name space}.
  6597. Thus, there is no name conflict in this code:
  6598.  
  6599. @example
  6600. struct pair @{ int a, b; @};
  6601. int pair = 1;
  6602. @end example
  6603.  
  6604. @noindent
  6605. nor in this one:
  6606.  
  6607. @example
  6608. struct pair @{ int a, b; @} pair;
  6609. @end example
  6610.  
  6611. @noindent
  6612. where @code{pair} is both a structure type tag and a variable name.
  6613.  
  6614. However, @code{struct}, @code{union}, and @code{enum} share the same
  6615. name space of tags, so this is a conflict:
  6616.  
  6617. @example
  6618. struct pair @{ int a, b; @};
  6619. enum pair @{ c, d @};
  6620. @end example
  6621.  
  6622. @noindent
  6623. and so is this:
  6624.  
  6625. @example
  6626. struct pair @{ int a, b; @};
  6627. struct pair @{ int c, d; @};
  6628. @end example
  6629.  
  6630. When the code defines a type tag inside a block, the tag's scope is
  6631. limited to that block (as for local variables).  Two definitions for
  6632. one type tag do not conflict if they are in different scopes; rather,
  6633. each is valid in its scope.  For example,
  6634.  
  6635. @example
  6636. struct pair @{ int a, b; @};
  6637.  
  6638. void
  6639. pair_up_doubles (int len, double array[])
  6640. @{
  6641.  struct pair @{ double a, b; @};
  6642.  @r{@dots{}}
  6643. @}
  6644. @end example
  6645. @noindent
  6646. has two definitions for @code{struct pair} which do not conflict.  The
  6647. one inside the function applies only within the definition of
  6648. @code{pair_up_doubles}.  Within its scope, that definition
  6649. @dfn{shadows} the outer definition.
  6650. If @code{struct pair} appears inside the function body, before the
  6651. inner definition, it refers to the outer definition---the only one
  6652. that has been seen at that point.  Thus, in this code,
  6653. @example
  6654. struct pair @{ int a, b; @};
  6655. void
  6656. pair_up_doubles (int len, double array[])
  6657. @{
  6658.  struct two_pairs @{ struct pair *p, *q; @};
  6659.  struct pair @{ double a, b; @};
  6660.  @r{@dots{}}
  6661. @}
  6662. @end example
  6663. @noindent
  6664. the structure @code{two_pairs} has pointers to the outer definition of
  6665. @code{struct pair}, which is probably not desirable.
  6666. To prevent that, you can write @code{struct pair;} inside the function
  6667. body as a variable declaration with no variables.  This is a
  6668. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  6669. type tag local to the current block, with the details of the type to
  6670. come later.  Here's an example:
  6671. @example
  6672. void
  6673. pair_up_doubles (int len, double array[])
  6674. @{
  6675.  /* @r{Forward declaration for @code{pair}.}  */
  6676.  struct pair;
  6677.  struct two_pairs @{ struct pair *p, *q; @};
  6678.  /* @r{Give the details.}  */
  6679.  struct pair @{ double a, b; @};
  6680.  @r{@dots{}}
  6681. @}
  6682. @end example
  6683. However, the cleanest practice is to avoid shadowing type tags.
  6684. @node Arrays
  6685. @chapter Arrays
  6686. @cindex array
  6687. @cindex elements of arrays
  6688. An @dfn{array} is a data object that holds a series of @dfn{elements},
  6689. all of the same data type.  Each element is identified by its numeric
  6690. @var{index} within the array.
  6691. We presented arrays of numbers in the sample programs early in this
  6692. manual (@pxref{Array Example}).  However, arrays can have elements of
  6693. any data type, including pointers, structures, unions, and other
  6694. arrays.
  6695. If you know another programming language, you may suppose that you know all
  6696. about arrays, but C arrays have special quirks, so in this chapter we
  6697. collect all the information about arrays in C@.
  6698. The elements of a C array are allocated consecutively in memory,
  6699. with no gaps between them.  Each element is aligned as required
  6700. for its data type (@pxref{Type Alignment}).
  6701. @menu
  6702. * Accessing Array Elements::     How to access individual elements of an array.
  6703. * Declaring an Array::           How to name and reserve space for a new array.
  6704. * Strings::                      A string in C is a special case of array.
  6705. * Array Type Designators::       Referring to a specific array type.
  6706. * Incomplete Array Types::       Naming, but not allocating, a new array.
  6707. * Limitations of C Arrays::      Arrays are not first-class objects.
  6708. * Multidimensional Arrays::      Arrays of arrays.
  6709. * Constructing Array Values::    Assigning values to an entire array at once.
  6710. * Arrays of Variable Length::    Declaring arrays of non-constant size.
  6711. @end menu
  6712. @node Accessing Array Elements
  6713. @section Accessing Array Elements
  6714. @cindex accessing array elements
  6715. @cindex array elements, accessing
  6716. If the variable @code{a} is an array, the @var{n}th element of
  6717. @code{a} is @code{a[@var{n}]}.  You can use that expression to access
  6718. an element's value or to assign to it:
  6719.  
  6720. @example
  6721. x = a[5];
  6722. a[6] = 1;
  6723. @end example
  6724.  
  6725. @noindent
  6726. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  6727. lvalue.
  6728.  
  6729. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  6730. valid index is one less than the number of elements.
  6731.  
  6732. The C language does not check whether array indices are in bounds, so
  6733. if the code uses an out-of-range index, it will access memory outside the
  6734. array.
  6735.  
  6736. @strong{Warning:} Using only valid index values in C is the
  6737. programmer's responsibility.
  6738.  
  6739. Array indexing in C is not a primitive operation: it is defined in
  6740. terms of pointer arithmetic and dereferencing.  Now that we know
  6741. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  6742. its job.
  6743.  
  6744. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  6745. @code{*(@var{x}+@var{y})}.  Thus, @code{a[i]} really means
  6746. @code{*(a+i)}.  @xref{Pointers and Arrays}.
  6747.  
  6748. When an expression with array type (such as @code{a}) appears as part
  6749. of a larger C expression, it is converted automatically to a pointer
  6750. to element zero of that array.  For instance, @code{a} in an
  6751. expression is equivalent to @code{&a[0]}.  Thus, @code{*(a+i)} is
  6752. computed as @code{*(&a[0]+i)}.
  6753.  
  6754. Now we can analyze how that expression gives us the desired element of
  6755. the array.  It makes a pointer to element 0 of @code{a}, advances it
  6756. by the value of @code{i}, and dereferences that pointer.
  6757.  
  6758. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  6759.  
  6760. @node Declaring an Array
  6761. @section Declaring an Array
  6762. @cindex declaring an array
  6763. @cindex array, declaring
  6764.  
  6765. To make an array declaration, write @code{[@var{length}]} after the
  6766. name being declared.  This construct is valid in the declaration of a
  6767. variable, a function parameter, a function value type (the value can't
  6768. be an array, but it can be a pointer to one), a structure field, or a
  6769. union alternative.
  6770.  
  6771. The surrounding declaration specifies the element type of the array;
  6772. that can be any type of data, but not @code{void} or a function type.
  6773. For instance,
  6774.  
  6775. @example
  6776. double a[5];
  6777. @end example
  6778.  
  6779. @noindent
  6780. declares @code{a} as an array of 5 @code{double}s.
  6781.  
  6782. @example
  6783. struct foo bstruct[length];
  6784. @end example
  6785.  
  6786. @noindent
  6787. declares @code{bstruct} as an array of @code{length} objects of type
  6788. @code{struct foo}.  A variable array size like this is allowed when
  6789. the array is not file-scope.
  6790.  
  6791. Other declaration constructs can nest within the array declaration
  6792. construct.  For instance:
  6793.  
  6794. @example
  6795. struct foo *b[length];
  6796. @end example
  6797.  
  6798. @noindent
  6799. declares @code{b} as an array of @code{length} pointers to
  6800. @code{struct foo}.  This shows that the length need not be a constant
  6801. (@pxref{Arrays of Variable Length}).
  6802.  
  6803. @example
  6804. double (*c)[5];
  6805. @end example
  6806.  
  6807. @noindent
  6808. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  6809.  
  6810. @example
  6811. char *(*f (int))[5];
  6812. @end example
  6813.  
  6814. @noindent
  6815. declares @code{f} as a function taking an @code{int} argument and
  6816. returning a pointer to an array of 5 strings (pointers to
  6817. @code{char}s).
  6818.  
  6819. @example
  6820. double aa[5][10];
  6821. @end example
  6822.  
  6823. @noindent
  6824. declares @code{aa} as an array of 5 elements, each of which is an
  6825. array of 10 @code{double}s.  This shows how to declare a
  6826. multidimensional array in C (@pxref{Multidimensional Arrays}).
  6827.  
  6828. All these declarations specify the array's length, which is needed in
  6829. these cases in order to allocate storage for the array.
  6830.  
  6831. @node Strings
  6832. @section Strings
  6833. @cindex string
  6834.  
  6835. A string in C is a sequence of elements of type @code{char},
  6836. terminated with the null character, the character with code zero.
  6837.  
  6838. Programs often need to use strings with specific, fixed contents.  To
  6839. write one in a C program, use a @dfn{string constant} such as
  6840. @code{"Take me to your leader!"}.  The data type of a string constant
  6841. is @code{char *}.  For the full syntactic details of writing string
  6842. constants, @ref{String Constants}.
  6843.  
  6844. To declare a place to store a non-constant string, declare an array of
  6845. @code{char}.  Keep in mind that it must include one extra @code{char}
  6846. for the terminating null.  For instance,
  6847.  
  6848. @example
  6849. char text = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  6850. @end example
  6851.  
  6852. @noindent
  6853. declares an array named @samp{text} with six elements---five letters
  6854. and the terminating null character.  An equivalent way to get the same
  6855. result is this,
  6856.  
  6857. @example
  6858. char text = "Hello";
  6859. @end example
  6860.  
  6861. @noindent
  6862. which copies the elements of the string constant, including @emph{its}
  6863. terminating null character.
  6864.  
  6865. @example
  6866. char message[200];
  6867. @end example
  6868.  
  6869. @noindent
  6870. declares an array long enough to hold a string of 199 ASCII characters
  6871. plus the terminating null character.
  6872.  
  6873. When you store a string into @code{message} be sure to check or prove
  6874. that the length does not exceed its size.  For example,
  6875.  
  6876. @example
  6877. void
  6878. set_message (char *text)
  6879. @{
  6880.  int i;
  6881.  for (i = 0; i < sizeof (message); i++)
  6882.    @{
  6883.      message[i] = text[i];
  6884.      if (text[i] == 0)
  6885.        return;
  6886.    @}
  6887.  fatal_error ("Message is too long for `message');
  6888. @}
  6889. @end example
  6890.  
  6891. It's easy to do this with the standard library function
  6892. @code{strncpy}, which fills out the whole destination array (up to a
  6893. specified length) with null characters.  Thus, if the last character
  6894. of the destination is not null, the string did not fit.  Many system
  6895. libraries, including the GNU C library, hand-optimize @code{strncpy}
  6896. to run faster than an explicit @code{for}-loop.
  6897.  
  6898. Here's what the code looks like:
  6899.  
  6900. @example
  6901. void
  6902. set_message (char *text)
  6903. @{
  6904.  strncpy (message, text, sizeof (message));
  6905.  if (message[sizeof (message) - 1] != 0)
  6906.    fatal_error ("Message is too long for `message');
  6907. @}
  6908. @end example
  6909.  
  6910. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  6911. Library Reference Manual}, for more information about the standard
  6912. library functions for operating on strings.
  6913.  
  6914. You can avoid putting a fixed length limit on strings you construct or
  6915. operate on by allocating the space for them dynamically.
  6916. @xref{Dynamic Memory Allocation}.
  6917.  
  6918. @node Array Type Designators
  6919. @section Array Type Designators
  6920.  
  6921. Every C type has a type designator, which you make by deleting the
  6922. variable name and the semicolon from a declaration (@pxref{Type
  6923. Designators}).  The designators for array types follow this rule, but
  6924. they may appear surprising.
  6925.  
  6926. @example
  6927. @r{type}   int a[5];           @r{designator}   int [5]
  6928. @r{type}   double a[5][3];     @r{designator}   double [5][3]
  6929. @r{type}   struct foo *a[5];   @r{designator}   struct foo *[5]
  6930. @end example
  6931.  
  6932. @node Incomplete Array Types
  6933. @section Incomplete Array Types
  6934. @cindex incomplete array types
  6935. @cindex array types, incomplete
  6936.  
  6937. An array is equivalent, for most purposes, to a pointer to its zeroth
  6938. element.  When that is true, the length of the array is irrelevant.
  6939. The length needs to be known only for allocating space for the array, or
  6940. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}).  Thus, in some
  6941. contexts C allows
  6942.  
  6943. @itemize @bullet
  6944. @item
  6945. An @code{extern} declaration says how to refer to a variable allocated
  6946. elsewhere.  It does not need to allocate space for the variable,
  6947. so if it is an array, you can omit the length.  For example,
  6948.  
  6949. @example
  6950. extern int foo[];
  6951. @end example
  6952. @item
  6953. When declaring a function parameter as an array, the argument value
  6954. passed to the function is really a pointer to the array's zeroth
  6955. element.  This value does not say how long the array really is, there
  6956. is no need to declare it.  For example,
  6957. @example
  6958. int
  6959. func (int foo[])
  6960. @end example
  6961. @end itemize
  6962. These declarations are examples of @dfn{incomplete} array types, types
  6963. that are not fully specified.  The incompleteness makes no difference
  6964. for accessing elements of the array, but it matters for some other
  6965. things.  For instance, @code{sizeof} is not allowed on an incomplete
  6966. type.
  6967. With multidimensional arrays, only the first dimension can be omitted:
  6968. @example
  6969. extern struct chesspiece *funnyboard foo[][8];
  6970. @end example
  6971.  
  6972. In other words, the code doesn't have to say how many rows there are,
  6973. but it must state how big each row is.
  6974.  
  6975. @node Limitations of C Arrays
  6976. @section Limitations of C Arrays
  6977. @cindex limitations of C arrays
  6978. @cindex first-class object
  6979.  
  6980. Arrays have quirks in C because they are not ``first-class objects'':
  6981. there is no way in C to operate on an array as a unit.
  6982.  
  6983. The other composite objects in C, structures and unions, are
  6984. first-class objects: a C program can copy a structure or union value
  6985. in an assignment, or pass one as an argument to a function, or make a
  6986. function return one.  You can't do those things with an array in C@.
  6987. That is because a value you can operate on never has an array type.
  6988.  
  6989. An expression in C can have an array type, but that doesn't produce
  6990. the array as a value.  Instead it is converted automatically to a
  6991. pointer to the array's element at index zero.  The code can operate
  6992. on the pointer, and through that on individual elements of the array,
  6993. but it can't get and operate on the array as a unit.
  6994.  
  6995. There are three exceptions to this conversion rule, but none of them
  6996. offers a way to operate on the array as a whole.
  6997.  
  6998. First, @samp{&} applied to an expression with array type gives you the
  6999. address of the array, as an array type.  However, you can't operate on the
  7000. whole array that way---if you apply @samp{*} to get the array back,
  7001. that expression converts, as usual, to a pointer to its zeroth
  7002. element.
  7003.  
  7004. Second, the operators @code{sizeof}, @code{_Alignof}, and
  7005. @code{typeof} do not convert the array to a pointer; they leave it as
  7006. an array.  But they don't operate on the array's data---they only give
  7007. information about its type.
  7008.  
  7009. Third, a string constant used as an initializer for an array is not
  7010. converted to a pointer---rather, the declaration copies the
  7011. @emph{contents} of that string in that one special case.
  7012.  
  7013. You @emph{can} copy the contents of an array, just not with an
  7014. assignment operator.  You can do it by calling the library function
  7015. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  7016. GNU C Library, , libc, The GNU C Library Reference Manual}).  Also,
  7017. when a structure contains just an array, you can copy that structure.
  7018.  
  7019. An array itself is an lvalue if it is a declared variable, or part of
  7020. a structure or union that is an lvalue.  When you construct an array
  7021. from elements (@pxref{Constructing Array Values}), that array is not
  7022. an lvalue.
  7023.  
  7024. @node Multidimensional Arrays
  7025. @section Multidimensional Arrays
  7026. @cindex multidimensional arrays
  7027. @cindex array, multidimensional
  7028.  
  7029. Strictly speaking, all arrays in C are unidimensional.  However, you
  7030. can create an array of arrays, which is more or less equivalent to a
  7031. multidimensional array.  For example,
  7032.  
  7033. @example
  7034. struct chesspiece *board[8][8];
  7035. @end example
  7036.  
  7037. @noindent
  7038. declares an array of 8 arrays of 8 pointers to @code{struct
  7039. chesspiece}.  This data type could represent the state of a chess
  7040. game.  To access one square's contents requires two array index
  7041. operations, one for each dimension.  For instance, you can write
  7042. @code{board[row][column]}, assuming @code{row} and @code{column}
  7043. are variables with integer values in the proper range.
  7044.  
  7045. How does C understand @code{board[row][column]}?  First of all,
  7046. @code{board} is converted automatically to a pointer to the zeroth
  7047. element (at index zero) of @code{board}.  Adding @code{row} to that
  7048. makes it point to the desired element.  Thus, @code{board[row]}'s
  7049. value is an element of @code{board}---an array of 8 pointers.
  7050.  
  7051. However, as an expression with array type, it is converted
  7052. automatically to a pointer to the array's zeroth element.  The second
  7053. array index operation, @code{[column]}, accesses the chosen element
  7054. from that array.
  7055.  
  7056. As this shows, pointer-to-array types are meaningful in C@.
  7057. You can declare a variable that points to a row in a chess board
  7058. like this:
  7059.  
  7060. @example
  7061. struct chesspiece *(*rowptr)[8];
  7062. @end example
  7063.  
  7064. @noindent
  7065. This points to an array of 8 pointers to @code{struct chesspiece}.
  7066. You can assign to it as follows:
  7067.  
  7068. @example
  7069. rowptr = &board[5];
  7070. @end example
  7071.  
  7072. The dimensions don't have to be equal in length.  Here we declare
  7073. @code{statepop} as an array to hold the population of each state in
  7074. the United States for each year since 1900:
  7075.  
  7076. @example
  7077. #define NSTATES 50
  7078. @{
  7079.  int nyears = current_year - 1900 + 1;
  7080.  int statepop[NSTATES][nyears];
  7081.  @r{@dots{}}
  7082. @}
  7083. @end example
  7084.  
  7085. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  7086. each indexed by the year (counting from 1900).  Thus, to get the
  7087. element for a particular state and year, we must subscript it first
  7088. by the number that indicates the state, and second by the index for
  7089. the year:
  7090.  
  7091. @example
  7092. statepop[state][year - 1900]
  7093. @end example
  7094.  
  7095. @cindex array, layout in memory
  7096. The subarrays within the multidimensional array are allocated
  7097. consecutively in memory, and within each subarray, its elements are
  7098. allocated consecutively in memory.  The most efficient way to process
  7099. all the elements in the array is to scan the last subscript in the
  7100. innermost loop.  This means consecutive accesses go to consecutive
  7101. memory locations, which optimizes use of the processor's memory cache.
  7102. For example:
  7103.  
  7104. @example
  7105. int total = 0;
  7106. float average;
  7107.  
  7108. for (int state = 0; state < NSTATES, ++state)
  7109.  @{
  7110.    for (int year = 0; year < nyears; ++year)
  7111.      @{
  7112.        total += statepop[state][year];
  7113.      @}
  7114.  @}
  7115.  
  7116. average = total / nyears;
  7117. @end example
  7118.  
  7119. C's layout for multidimensional arrays is different from Fortran's
  7120. layout.  In Fortran, a multidimensional array is not an array of
  7121. arrays; rather, multidimensional arrays are a primitive feature, and
  7122. it is the first index that varies most rapidly between consecutive
  7123. memory locations.  Thus, the memory layout of a 50x114 array in C
  7124. matches that of a 114x50 array in Fortran.
  7125.  
  7126. @node Constructing Array Values
  7127. @section Constructing Array Values
  7128. @cindex constructing array values
  7129. @cindex array values, constructing
  7130.  
  7131. You can construct an array from elements by writing them inside
  7132. braces, and preceding all that with the array type's designator in
  7133. parentheses.  There is no need to specify the array length, since the
  7134. number of elements determines that.  The constructor looks like this:
  7135.  
  7136. @example
  7137. (@var{elttype}[]) @{ @var{elements} @};
  7138. @end example
  7139. Here is an example, which constructs an array of string pointers:
  7140. @example
  7141. (char *[]) @{ "x", "y", "z" @};
  7142. @end example
  7143. That's equivalent in effect to declaring an array with the same
  7144. initializer, like this:
  7145. @example
  7146. char *array[] = @{ "x", "y", "z" @};
  7147. @end example
  7148. and then using the array.
  7149. If all the elements are simple constant expressions, or made up of
  7150. such, then the compound literal can be coerced to a pointer to its
  7151. zeroth element and used to initialize a file-scope variable
  7152. (@pxref{File-Scope Variables}), as shown here:
  7153. @example
  7154. char **foo = (char *[]) @{ "x", "y", "z" @};
  7155. @end example
  7156. @noindent
  7157. The data type of @code{foo} is @code{char **}, which is a pointer
  7158. type, not an array type.  The declaration is equivalent to defining
  7159. and then using an array-type variable:
  7160. @example
  7161. char *nameless_array[] = @{ "x", "y", "z" @};
  7162. char **foo = &nameless_array[0];
  7163. @end example
  7164.  
  7165. @node Arrays of Variable Length
  7166. @section Arrays of Variable Length
  7167. @cindex array of variable length
  7168. @cindex variable-length arrays
  7169.  
  7170. In GNU C, you can declare variable-length arrays like any other
  7171. arrays, but with a length that is not a constant expression.  The
  7172. storage is allocated at the point of declaration and deallocated when
  7173. the block scope containing the declaration exits.  For example:
  7174.  
  7175. @example
  7176. #include <stdio.h>  /* @r{Defines @code{FILE}.} */
  7177. #include <string.h> /* @r{Declares @code{str}.} */
  7178.  
  7179. FILE *
  7180. concat_fopen (char *s1, char *s2, char *mode)
  7181. @{
  7182.  char str[strlen (s1) + strlen (s2) + 1];
  7183.  strcpy (str, s1);
  7184.  strcat (str, s2);
  7185.  return fopen (str, mode);
  7186. @}
  7187. @end example
  7188.  
  7189. @noindent
  7190. (This uses some standard library functions; see @ref{String and Array
  7191. Utilities, , , libc, The GNU C Library Reference Manual}.)
  7192.  
  7193. The length of an array is computed once when the storage is allocated
  7194. and is remembered for the scope of the array in case it is used in
  7195. @code{sizeof}.
  7196.  
  7197. @strong{Warning:} don't allocate a variable-length array if the size
  7198. might be very large (more than 100,000), or in a recursive function,
  7199. because that is likely to cause stack overflow.  Allocate the array
  7200. dynamically instead (@pxref{Dynamic Memory Allocation}).
  7201.  
  7202. Jumping or breaking out of the scope of the array name deallocates the
  7203. storage.  Jumping into the scope is not allowed; that gives an error
  7204. message.
  7205.  
  7206. You can also use variable-length arrays as arguments to functions:
  7207.  
  7208. @example
  7209. struct entry
  7210. tester (int len, char data[len][len])
  7211. @{
  7212.  @r{@dots{}}
  7213. @}
  7214. @end example
  7215.  
  7216. As usual, a function argument declared with an array type
  7217. is really a pointer to an array that already exists.
  7218. Calling the function does not allocate the array, so there's no
  7219. particular danger of stack overflow in using this construct.
  7220.  
  7221. To pass the array first and the length afterward, use a forward
  7222. declaration in the function's parameter list (another GNU extension).
  7223. For example,
  7224.  
  7225. @example
  7226. struct entry
  7227. tester (int len; char data[len][len], int len)
  7228. @{
  7229.  @r{@dots{}}
  7230. @}
  7231. @end example
  7232.  
  7233. The @code{int len} before the semicolon is a @dfn{parameter forward
  7234. declaration}, and it serves the purpose of making the name @code{len}
  7235. known when the declaration of @code{data} is parsed.
  7236.  
  7237. You can write any number of such parameter forward declarations in the
  7238. parameter list.  They can be separated by commas or semicolons, but
  7239. the last one must end with a semicolon, which is followed by the
  7240. ``real'' parameter declarations.  Each forward declaration must match
  7241. a ``real'' declaration in parameter name and data type.  ISO C11 does
  7242. not support parameter forward declarations.
  7243.  
  7244. @node Enumeration Types
  7245. @chapter Enumeration Types
  7246. @cindex enumeration types
  7247. @cindex types, enumeration
  7248. @cindex enumerator
  7249.  
  7250. An @dfn{enumeration type} represents a limited set of integer values,
  7251. each with a name.  It is effectively equivalent to a primitive integer
  7252. type.
  7253.  
  7254. Suppose we have a list of possible emotional states to store in an
  7255. integer variable.  We can give names to these alternative values with
  7256. an enumeration:
  7257.  
  7258. @example
  7259. enum emotion_state @{ neutral, happy, sad, worried,
  7260.                     calm, nervous @};
  7261. @end example
  7262.  
  7263. @noindent
  7264. (Never mind that this is a simplistic way to classify emotional states;
  7265. it's just a code example.)
  7266.  
  7267. The names inside the enumeration are called @dfn{enumerators}.  The
  7268. enumeration type defines them as constants, and their values are
  7269. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  7270. @code{sad} is 2, and so on.  Alternatively, you can specify values for
  7271. the enumerators explicitly like this:
  7272.  
  7273. @example
  7274. enum emotion_state @{ neutral = 2, happy = 5,
  7275.                     sad = 20, worried = 10,
  7276.                     calm = -5, nervous = -300 @};
  7277. @end example
  7278.  
  7279. Each enumerator which does not specify a value gets value zero
  7280. (if it is at the beginning) or the next consecutive integer.
  7281.  
  7282. @example
  7283. /* @r{@code{neutral} is 0 by default,}
  7284.   @r{and @code{worried} is 21 by default.}  */
  7285. enum emotion_state @{ neutral,
  7286.                      happy = 5, sad = 20, worried,
  7287.                      calm = -5, nervous = -300 @};
  7288. @end example
  7289.  
  7290. If an enumerator is obsolete, you can specify that using it should
  7291. cause a warning, by including an attribute in the enumerator's
  7292. declaration.  Here is how @code{happy} would look with this
  7293. attribute:
  7294.  
  7295. @example
  7296. happy __attribute__
  7297.      ((deprecated
  7298.        ("impossible under plutocratic rule")))
  7299.      = 5,
  7300. @end example
  7301.  
  7302. @xref{Attributes}.
  7303.  
  7304. You can declare variables with the enumeration type:
  7305.  
  7306. @example
  7307. enum emotion_state feelings_now;
  7308. @end example
  7309.  
  7310. In the C code itself, this is equivalent to declaring the variable
  7311. @code{int}.  (If all the enumeration values are positive, it is
  7312. equivalent to @code{unsigned int}.)  However, declaring it with the
  7313. enumeration type has an advantage in debugging, because GDB knows it
  7314. should display the current value of the variable using the
  7315. corresponding name.  If the variable's type is @code{int}, GDB can
  7316. only show the value as a number.
  7317.  
  7318. The identifier that follows @code{enum} is called a @dfn{type tag}
  7319. since it distinguishes different enumeration types.  Type tags are in
  7320. a separate name space and belong to scopes like most other names in C@.
  7321. @xref{Type Tags}, for explanation.
  7322.  
  7323. You can predeclare an @code{enum} type tag like a structure or union
  7324. type tag, like this:
  7325.  
  7326. @example
  7327. enum foo;
  7328. @end example
  7329.  
  7330. @noindent
  7331. The @code{enum} type is incomplete until you finish defining it.
  7332.  
  7333. You can optionally include a trailing comma at the end of a list of
  7334. enumeration values:
  7335.  
  7336. @example
  7337. enum emotion_state @{ neutral, happy, sad, worried,
  7338.                     calm, nervous, @};
  7339. @end example
  7340.  
  7341. @noindent
  7342. This is useful in some macro definitions, since it enables you to
  7343. assemble the list of enumerators without knowing which one is last.
  7344. The extra comma does not change the meaning of the enumeration in any
  7345. way.
  7346.  
  7347. @node Defining Typedef Names
  7348. @chapter Defining Typedef Names
  7349. @cindex typedef names
  7350. @findex typedef
  7351.  
  7352. You can define a data type keyword as an alias for any type, and then
  7353. use the alias syntactically like a built-in type keyword such as
  7354. @code{int}.  You do this using @code{typedef}, so these aliases are
  7355. also called @dfn{typedef names}.
  7356.  
  7357. @code{typedef} is followed by text that looks just like a variable
  7358. declaration, but instead of declaring variables it defines data type
  7359. keywords.
  7360.  
  7361. Here's how to define @code{fooptr} as a typedef alias for the type
  7362. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  7363. with that type:
  7364.  
  7365. @example
  7366. typedef struct foo *fooptr;
  7367.  
  7368. fooptr x, y;
  7369. @end example
  7370.  
  7371. @noindent
  7372. That declaration is equivalent to the following one:
  7373.  
  7374. @example
  7375. struct foo *x, *y;
  7376. @end example
  7377.  
  7378. You can define a typedef alias for any type.  For instance, this makes
  7379. @code{frobcount} an alias for type @code{int}:
  7380.  
  7381. @example
  7382. typedef int frobcount;
  7383. @end example
  7384.  
  7385. @noindent
  7386. This doesn't define a new type distinct from @code{int}.  Rather,
  7387. @code{frobcount} is another name for the type @code{int}.  Once the
  7388. variable is declared, it makes no difference which name the
  7389. declaration used.
  7390.  
  7391. There is a syntactic difference, however, between @code{frobcount} and
  7392. @code{int}: A typedef name cannot be used with
  7393. @code{signed}, @code{unsigned}, @code{long} or @code{short}.  It has
  7394. to specify the type all by itself.  So you can't write this:
  7395.  
  7396. @example
  7397. unsigned frobcount f1;  /* @r{Error!} */
  7398. @end example
  7399.  
  7400. But you can write this:
  7401.  
  7402. @example
  7403. typedef unsigned int unsigned_frobcount;
  7404.  
  7405. unsigned_frobcount f1;
  7406. @end example
  7407.  
  7408. In other words, a typedef name is not an alias for @emph{a keyword}
  7409. such as @code{int}.  It stands for a @emph{type}, and that could be
  7410. the type @code{int}.
  7411.  
  7412. Typedef names are in the same namespace as functions and variables, so
  7413. you can't use the same name for a typedef and a function, or a typedef
  7414. and a variable.  When a typedef is declared inside a code block, it is
  7415. in scope only in that block.
  7416.  
  7417. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  7418. because many of these have standard meanings.
  7419.  
  7420. You can redefine a typedef name to the exact same type as its first
  7421. definition, but you cannot redefine a typedef name to a
  7422. different type, even if the two types are compatible. For example, this
  7423. is valid:
  7424.  
  7425. @example
  7426. typedef int frobcount;
  7427. typedef int frotzcount;
  7428. typedef frotzcount frobcount;
  7429. typedef frobcount frotzcount;
  7430. @end example
  7431.  
  7432. @noindent
  7433. because each typedef name is always defined with the same type
  7434. (@code{int}), but this is not valid:
  7435.  
  7436. @example
  7437. enum foo @{f1, f2, f3@};
  7438. typedef enum foo frobcount;
  7439. typedef int frobcount;
  7440. @end example
  7441.  
  7442. @noindent
  7443. Even though the type @code{enum foo} is compatible with @code{int},
  7444. they are not the @emph{same} type.
  7445.  
  7446. @node Statements
  7447. @chapter Statements
  7448. @cindex statements
  7449.  
  7450. A @dfn{statement} specifies computations to be done for effect; it
  7451. does not produce a value, as an expression would.  In general a
  7452. statement ends with a semicolon (@samp{;}), but blocks (which are
  7453. statements, more or less) are an exception to that rule.
  7454. @ifnottex
  7455. @xref{Blocks}.
  7456. @end ifnottex
  7457.  
  7458. The places to use statements are inside a block, and inside a
  7459. complex statement.  A @dfn{complex statement} contains one or two
  7460. components that are nested statements.  Each such component must
  7461. consist of one and only one statement.  The way to put multiple
  7462. statements in such a component is to group them into a @dfn{block}
  7463. (@pxref{Blocks}), which counts as one statement.
  7464.  
  7465. The following sections describe the various kinds of statement.
  7466.  
  7467. @menu
  7468. * Expression Statement::         Evaluate an expression, as a statement,
  7469.                                   usually done for a side effect.
  7470. * if Statement::                 Basic conditional execution.
  7471. * if-else Statement::            Multiple branches for conditional execution.
  7472. * Blocks::                       Grouping multiple statements together.
  7473. * return Statement::             Return a value from a function.
  7474. * Loop Statements::              Repeatedly executing a statement or block.
  7475. * switch Statement::             Multi-way conditional choices.
  7476. * switch Example::               A plausible example of using @code{switch}.
  7477. * Duffs Device::                 A special way to use @code{switch}.
  7478. * Case Ranges::                  Ranges of values for @code{switch} cases.
  7479. * Null Statement::               A statement that does nothing.
  7480. * goto Statement::               Jump to another point in the source code,
  7481.                                   identified by a label.
  7482. * Local Labels::                 Labels with limited scope.
  7483. * Labels as Values::             Getting the address of a label.
  7484. * Statement Exprs::              A series of statements used as an expression.
  7485. @end menu
  7486.  
  7487. @node Expression Statement
  7488. @section Expression Statement
  7489. @cindex expression statement
  7490. @cindex statement, expression
  7491.  
  7492. The most common kind of statement in C is an @dfn{expression statement}.
  7493. It consists of an expression followed by a
  7494. semicolon.  The expression's value is discarded, so the expressions
  7495. that are useful are those that have side effects: assignment
  7496. expressions, increment and decrement expressions, and function calls.
  7497. Here are examples of expression statements:
  7498.  
  7499. @smallexample
  7500. x = 5;              /* @r{Assignment expression.} */
  7501. p++;                /* @r{Increment expression.} */
  7502. printf ("Done\n");  /* @r{Function call expression.} */
  7503. *p;                 /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  7504. x + y;              /* @r{Useless statement without effect.} */
  7505. @end smallexample
  7506.  
  7507. In very unusual circumstances we use an expression statement
  7508. whose purpose is to get a fault if an address is invalid:
  7509.  
  7510. @smallexample
  7511. volatile char *p;
  7512. @r{@dots{}}
  7513. *p;                 /* @r{Cause signal if @code{p} is null.} */
  7514. @end smallexample
  7515.  
  7516. If the target of @code{p} is not declared @code{volatile}, the
  7517. compiler might optimize away the memory access, since it knows that
  7518. the value isn't really used.  @xref{volatile}.
  7519.  
  7520. @node if Statement
  7521. @section @code{if} Statement
  7522. @cindex @code{if} statement
  7523. @cindex statement, @code{if}
  7524. @findex if
  7525.  
  7526. An @code{if} statement computes an expression to decide
  7527. whether to execute the following statement or not.
  7528. It looks like this:
  7529.  
  7530. @example
  7531. if (@var{condition})
  7532.  @var{execute-if-true}
  7533. @end example
  7534.  
  7535. The first thing this does is compute the value of @var{condition}.  If
  7536. that is true (nonzero), then it executes the statement
  7537. @var{execute-if-true}.  If the value of @var{condition} is false
  7538. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  7539. nothing.
  7540.  
  7541. This is a @dfn{complex statement} because it contains a component
  7542. @var{if-true-substatement} that is a nested statement.  It must be one
  7543. and only one statement.  The way to put multiple statements there is
  7544. to group them into a @dfn{block} (@pxref{Blocks}).
  7545.  
  7546. @node if-else Statement
  7547. @section @code{if-else} Statement
  7548. @cindex @code{if}@dots{}@code{else} statement
  7549. @cindex statement, @code{if}@dots{}@code{else}
  7550. @findex else
  7551.  
  7552. An @code{if}-@code{else} statement computes an expression to decide
  7553. which of two nested statements to execute.
  7554. It looks like this:
  7555.  
  7556. @example
  7557. if (@var{condition})
  7558.  @var{if-true-substatement}
  7559. else
  7560.  @var{if-false-substatement}
  7561. @end example
  7562.  
  7563. The first thing this does is compute the value of @var{condition}.  If
  7564. that is true (nonzero), then it executes the statement
  7565. @var{if-true-substatement}.  If the value of @var{condition} is false
  7566. (zero), then it executes the statement @var{if-false-substatement} instead.
  7567.  
  7568. This is a @dfn{complex statement} because it contains components
  7569. @var{if-true-substatement} and @var{if-else-substatement} that are
  7570. nested statements.  Each must be one and only one statement.  The way
  7571. to put multiple statements in such a component is to group them into a
  7572. @dfn{block} (@pxref{Blocks}).
  7573.  
  7574. @node Blocks
  7575. @section Blocks
  7576. @cindex block
  7577. @cindex compound statement
  7578.  
  7579. A @dfn{block} is a construct that contains multiple statements of any
  7580. kind.  It begins with @samp{@{} and ends with @samp{@}}, and has a
  7581. series of statements and declarations in between.  Another name for
  7582. blocks is @dfn{compound statements}.
  7583.  
  7584. Is a block a statement?  Yes and no.  It doesn't @emph{look} like a
  7585. normal statement---it does not end with a semicolon.  But you can
  7586. @emph{use} it like a statement; anywhere that a statement is required
  7587. or allowed, you can write a block and consider that block a statement.
  7588.  
  7589. So far it seems that a block is a kind of statement with an unusual
  7590. syntax.  But that is not entirely true: a function body is also a
  7591. block, and that block is definitely not a statement.  The text after a
  7592. function header is not treated as a statement; only a function body is
  7593. allowed there, and nothing else would be meaningful there.
  7594.  
  7595. In a formal grammar we would have to choose---either a block is a kind
  7596. of statement or it is not.  But this manual is meant for humans, not
  7597. for parser generators.  The clearest answer for humans is, ``a block
  7598. is a statement, in some ways.''
  7599.  
  7600. @cindex nested block
  7601. @cindex internal block
  7602. A block that isn't a function body is called an @dfn{internal block}
  7603. or a @dfn{nested block}.  You can put a nested block directly inside
  7604. another block, but more often the nested block is inside some complex
  7605. statement, such as a @code{for} statement or an @code{if} statement.
  7606.  
  7607. There are two uses for nested blocks in C:
  7608.  
  7609. @itemize @bullet
  7610. @item
  7611. To specify the scope for local declarations.  For instance, a local
  7612. variable's scope is the rest of the innermost containing block.
  7613.  
  7614. @item
  7615. To write a series of statements where, syntactically, one statement is
  7616. called for.  For instance, the @var{execute-if-true} of an @code{if}
  7617. statement is one statement.  To put multiple statements there, they
  7618. have to be wrapped in a block, like this:
  7619.  
  7620. @example
  7621. if (x < 0)
  7622.  @{
  7623.    printf ("x was negative\n");
  7624.    x = -x;
  7625.  @}
  7626. @end example
  7627. @end itemize
  7628.  
  7629. This example (repeated from above) shows a nested block which serves
  7630. both purposes: it includes two statements (plus a declaration) in the
  7631. body of a @code{while} statement, and it provides the scope for the
  7632. declaration of @code{q}.
  7633.  
  7634. @example
  7635. void
  7636. free_intlist (struct intlistlink *p)
  7637. @{
  7638.  while (p)
  7639.    @{
  7640.      struct intlistlink *q = p;
  7641.      p = p->next;
  7642.      free (q);
  7643.    @}
  7644. @}
  7645. @end example
  7646.  
  7647. @node return Statement
  7648. @section @code{return} Statement
  7649. @cindex @code{return} statement
  7650. @cindex statement, @code{return}
  7651. @findex return
  7652.  
  7653. The @code{return} statement makes the containing function return
  7654. immediately.  It has two forms.  This one specifies no value to
  7655. return:
  7656.  
  7657. @example
  7658. return;
  7659. @end example
  7660.  
  7661. @noindent
  7662. That form is meant for functions whose return type is @code{void}
  7663. (@pxref{The Void Type}).  You can also use it in a function that
  7664. returns nonvoid data, but that's a bad idea, since it makes the
  7665. function return garbage.
  7666.  
  7667. The form that specifies a value looks like this:
  7668.  
  7669. @example
  7670. return @var{value};
  7671. @end example
  7672.  
  7673. @noindent
  7674. which computes the expression @var{value} and makes the function
  7675. return that.  If necessary, the value undergoes type conversion to
  7676. the function's declared return value type, which works like
  7677. assigning the value to a variable of that type.
  7678.  
  7679. @node Loop Statements
  7680. @section Loop Statements
  7681. @cindex loop statements
  7682. @cindex statements, loop
  7683. @cindex iteration
  7684.  
  7685. You can use a loop statement when you need to execute a series of
  7686. statements repeatedly, making an @dfn{iteration}.  C provides several
  7687. different kinds of loop statements, described in the following
  7688. subsections.
  7689.  
  7690. Every kind of loop statement is a complex statement because contains a
  7691. component, here called @var{body}, which is a nested statement.
  7692. Most often the body is a block.
  7693.  
  7694. @menu
  7695. * while Statement::           Loop as long as a test expression is true.
  7696. * do-while Statement::        Execute a loop once, with further looping
  7697.                                as long as a test expression is true.
  7698. * break Statement::           End a loop immediately.
  7699. * for Statement::             Iterative looping.
  7700. * Example of for::            An example of iterative looping.
  7701. * Omitted for-Expressions::   for-loop expression options.
  7702. * for-Index Declarations::    for-loop declaration options.
  7703. * continue Statement::        Begin the next cycle of a loop.
  7704. @end menu
  7705.  
  7706. @node while Statement
  7707. @subsection @code{while} Statement
  7708. @cindex @code{while} statement
  7709. @cindex statement, @code{while}
  7710. @findex while
  7711.  
  7712. The @code{while} statement is the simplest loop construct.
  7713. It looks like this:
  7714.  
  7715. @example
  7716. while (@var{test})
  7717.  @var{body}
  7718. @end example
  7719.  
  7720. Here, @var{body} is a statement (often a nested block) to repeat, and
  7721. @var{test} is the test expression that controls whether to repeat it again.
  7722. Each iteration of the loop starts by computing @var{test} and, if it
  7723. is true (nonzero), that means the loop should execute @var{body} again
  7724. and then start over.
  7725.  
  7726. Here's an example of advancing to the last structure in a chain of
  7727. structures chained through the @code{next} field:
  7728.  
  7729. @example
  7730. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  7731. @r{@dots{}}
  7732. while (chain->next != NULL)
  7733.  chain = chain->next;
  7734. @end example
  7735.  
  7736. @noindent
  7737. This code assumes the chain isn't empty to start with; if the chain is
  7738. empty (that is, if @code{chain} is a null pointer), the code gets a
  7739. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  7740.  
  7741. @node do-while Statement
  7742. @subsection @code{do-while} Statement
  7743. @cindex @code{do}--@code{while} statement
  7744. @cindex statement, @code{do}--@code{while}
  7745. @findex do
  7746.  
  7747. The @code{do}--@code{while} statement is a simple loop construct that
  7748. performs the test at the end of the iteration.
  7749.  
  7750. @example
  7751. do
  7752.  @var{body}
  7753. while (@var{test});
  7754. @end example
  7755.  
  7756. Here, @var{body} is a statement (possibly a block) to repeat, and
  7757. @var{test} is an expression that controls whether to repeat it again.
  7758.  
  7759. Each iteration of the loop starts by executing @var{body}.  Then it
  7760. computes @var{test} and, if it is true (nonzero), that means to go
  7761. back and start over with @var{body}.  If @var{test} is false (zero),
  7762. then the loop stops repeating and execution moves on past it.
  7763.  
  7764. @node break Statement
  7765. @subsection @code{break} Statement
  7766. @cindex @code{break} statement
  7767. @cindex statement, @code{break}
  7768. @findex break
  7769.  
  7770. The @code{break} statement looks like @samp{break;}.  Its effect is to
  7771. exit immediately from the innermost loop construct or @code{switch}
  7772. statement (@pxref{switch Statement}).
  7773.  
  7774. For example, this loop advances @code{p} until the next null
  7775. character or newline.
  7776.  
  7777. @example
  7778. while (*p)
  7779.  @{
  7780.    /* @r{End loop if we have reached a newline.}  */
  7781.    if (*p == '\n')
  7782.      break;
  7783.    p++
  7784.  @}
  7785. @end example
  7786.  
  7787. When there are nested loops, the @code{break} statement exits from the
  7788. innermost loop containing it.
  7789.  
  7790. @example
  7791. struct list_if_tuples
  7792. @{
  7793.  struct list_if_tuples next;
  7794.  int length;
  7795.  data *contents;
  7796. @};
  7797.  
  7798. void
  7799. process_all_elements (struct list_if_tuples *list)
  7800. @{
  7801.  while (list)
  7802.    @{
  7803.      /* @r{Process all the elements in this node's vector,}
  7804.         @r{stopping when we reach one that is null.}  */
  7805.      for (i = 0; i < list->length; i++
  7806.        @{
  7807.          /* @r{Null element terminates this node's vector.}  */
  7808.          if (list->contents[i] == NULL)
  7809.            /* @r{Exit the @code{for} loop.}  */
  7810.            break;
  7811.          /* @r{Operate on the next element.}  */
  7812.          process_element (list->contents[i]);
  7813.        @}
  7814.  
  7815.      list = list->next;
  7816.    @}
  7817. @}
  7818. @end example
  7819.  
  7820. The only way in C to exit from an outer loop is with
  7821. @code{goto} (@pxref{goto Statement}).
  7822.  
  7823. @node for Statement
  7824. @subsection @code{for} Statement
  7825. @cindex @code{for} statement
  7826. @cindex statement, @code{for}
  7827. @findex for
  7828.  
  7829. A @code{for} statement uses three expressions written inside a
  7830. parenthetical group to define the repetition of the loop.  The first
  7831. expression says how to prepare to start the loop.  The second says how
  7832. to test, before each iteration, whether to continue looping.  The
  7833. third says how to advance, at the end of an iteration, for the next
  7834. iteration.  All together, it looks like this:
  7835.  
  7836. @example
  7837. for (@var{start}; @var{continue-test}; @var{advance})
  7838.  @var{body}
  7839. @end example
  7840.  
  7841. The first thing the @code{for} statement does is compute @var{start}.
  7842. The next thing it does is compute the expression @var{continue-test}.
  7843. If that expression is false (zero), the @code{for} statement finishes
  7844. immediately, so @var{body} is executed zero times.
  7845.  
  7846. However, if @var{continue-test} is true (nonzero), the @code{for}
  7847. statement executes @var{body}, then @var{advance}.  Then it loops back
  7848. to the not-quite-top to test @var{continue-test} again.  But it does
  7849. not compute @var{start} again.
  7850.  
  7851. @node Example of for
  7852. @subsection Example of @code{for}
  7853.  
  7854. Here is the @code{for} statement from the iterative Fibonacci
  7855. function:
  7856.  
  7857. @example
  7858. int i;
  7859. for (i = 1; i < n; ++i)
  7860.  /* @r{If @code{n} is 1 or less, the loop runs zero times,}  */
  7861.  /* @r{since @code{i < n} is false the first time.}  */
  7862.  @{
  7863.    /* @r{Now @var{last} is @code{fib (@var{i})}}
  7864.       @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.}  */
  7865.    /* @r{Compute @code{fib (@var{i} + 1)}.}  */
  7866.    int next = prev + last;
  7867.    /* @r{Shift the values down.}  */
  7868.    prev = last;
  7869.    last = next;
  7870.    /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  7871.       @r{and @var{prev} is @code{fib (@var{i})}.}
  7872.       @r{But that won't stay true for long,}
  7873.       @r{because we are about to increment @var{i}.}  */
  7874.  @}
  7875. @end example
  7876.  
  7877. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  7878. 1.  @var{continue-test} is @code{i < n}, meaning keep repeating the
  7879. loop as long as @code{i} is less than @code{n}.  @var{advance} is
  7880. @code{i++}, meaning increment @code{i} by 1.  The body is a block
  7881. that contains a declaration and two statements.
  7882.  
  7883. @node Omitted for-Expressions
  7884. @subsection Omitted @code{for}-Expressions
  7885.  
  7886. A fully-fleshed @code{for} statement contains all these parts,
  7887.  
  7888. @example
  7889. for (@var{start}; @var{continue-test}; @var{advance})
  7890.  @var{body}
  7891. @end example
  7892.  
  7893. @noindent
  7894. but you can omit any of the three expressions inside the parentheses.
  7895. The parentheses and the two semicolons are required syntactically, but
  7896. the expressions between them may be missing.  A missing expression
  7897. means this loop doesn't use that particular feature of the @code{for}
  7898. statement.
  7899.  
  7900. Instead of using @var{start}, you can do the loop preparation
  7901. before the @code{for} statement: the effect is the same.  So we
  7902. could have written the beginning of the previous example this way:
  7903.  
  7904. @example
  7905. int i = 0;
  7906. for (; i < n; ++i)
  7907. @end example
  7908.  
  7909. @noindent
  7910. instead of this way:
  7911.  
  7912. @example
  7913. int i;
  7914. for (i = 0; i < n; ++i)
  7915. @end example
  7916.  
  7917. Omitting @var{continue-test} means the loop runs forever (or until
  7918. something else causes exit from it).  Statements inside the loop can
  7919. test conditions for termination and use @samp{break;} to exit.  This
  7920. is more flexible since you can put those tests anywhere in the loop,
  7921. not solely at the beginning.
  7922.  
  7923. Putting an expression in @var{advance} is almost equivalent to writing
  7924. it at the end of the loop body; it does almost the same thing.  The
  7925. only difference is for the @code{continue} statement (@pxref{continue
  7926. Statement}).  So we could have written this:
  7927.  
  7928. @example
  7929. for (i = 0; i < n;)
  7930.  @{
  7931.    @r{@dots{}}
  7932.    ++i;
  7933.  @}
  7934. @end example
  7935.  
  7936. @noindent
  7937. instead of this:
  7938.  
  7939. @example
  7940. for (i = 0; i < n; ++i)
  7941.  @{
  7942.    @r{@dots{}}
  7943.  @}
  7944. @end example
  7945.  
  7946. The choice is mainly a matter of what is more readable for
  7947. programmers.  However, there is also a syntactic difference:
  7948. @var{advance} is an expression, not a statement.  It can't include
  7949. loops, blocks, declarations, etc.
  7950.  
  7951. @node for-Index Declarations
  7952. @subsection @code{for}-Index Declarations
  7953.  
  7954. You can declare loop-index variables directly in the @var{start}
  7955. portion of the @code{for}-loop, like this:
  7956.  
  7957. @example
  7958. for (int i = 0; i < n; ++i)
  7959.  @{
  7960.    @r{@dots{}}
  7961.  @}
  7962. @end example
  7963.  
  7964. This kind of @var{start} is limited to a single declaration; it can
  7965. declare one or more variables, separated by commas, all of which are
  7966. the same @var{basetype} (@code{int}, in this example):
  7967.  
  7968. @example
  7969. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  7970.  @{
  7971.    @r{@dots{}}
  7972.  @}
  7973. @end example
  7974.  
  7975. @noindent
  7976. The scope of these variables is the @code{for} statement as a whole.
  7977. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  7978.  
  7979. Variables declared in @code{for} statements should have initializers.
  7980. Omitting the initialization gives the variables unpredictable initial
  7981. values, so this code is erroneous.
  7982.  
  7983. @example
  7984. for (int i; i < n; ++i)
  7985.  @{
  7986.    @r{@dots{}}
  7987.  @}
  7988. @end example
  7989.  
  7990. @node continue Statement
  7991. @subsection @code{continue} Statement
  7992. @cindex @code{continue} statement
  7993. @cindex statement, @code{continue}
  7994. @findex continue
  7995.  
  7996. The @code{continue} statement looks like @samp{continue;}, and its
  7997. effect is to jump immediately to the end of the innermost loop
  7998. construct.  If it is a @code{for}-loop, the next thing that happens
  7999. is to execute the loop's @var{advance} expression.
  8000.  
  8001. For example, this loop increments @code{p} until the next null character
  8002. or newline, and operates (in some way not shown) on all the characters
  8003. in the line except for spaces.  All it does with spaces is skip them.
  8004.  
  8005. @example
  8006. for (;*p; ++p)
  8007.  @{
  8008.    /* @r{End loop if we have reached a newline.}  */
  8009.    if (*p == '\n')
  8010.      break;
  8011.    /* @r{Pay no attention to spaces.}  */
  8012.    if (*p == ' ')
  8013.      continue;
  8014.    /* @r{Operate on the next character.}  */
  8015.    @r{@dots{}}
  8016.  @}
  8017. @end example
  8018.  
  8019. @noindent
  8020. Executing @samp{continue;} skips the loop body but it does not
  8021. skip the @var{advance} expression, @code{p++}.
  8022.  
  8023. We could also write it like this:
  8024.  
  8025. @example
  8026. for (;*p; ++p)
  8027.  @{
  8028.    /* @r{Exit if we have reached a newline.}  */
  8029.    if (*p == '\n')
  8030.      break;
  8031.    /* @r{Pay no attention to spaces.}  */
  8032.    if (*p != ' ')
  8033.      @{
  8034.        /* @r{Operate on the next character.}  */
  8035.        @r{@dots{}}
  8036.      @}
  8037.  @}
  8038. @end example
  8039.  
  8040. The advantage of using @code{continue} is that it reduces the
  8041. depth of nesting.
  8042.  
  8043. Contrast @code{continue} with the @code{break} statement.  @xref{break
  8044. Statement}.
  8045.  
  8046. @node switch Statement
  8047. @section @code{switch} Statement
  8048. @cindex @code{switch} statement
  8049. @cindex statement, @code{switch}
  8050. @findex switch
  8051. @findex case
  8052. @findex default
  8053.  
  8054. The @code{switch} statement selects code to run according to the value
  8055. of an expression.  The expression, in parentheses, follows the keyword
  8056. @code{switch}.  After that come all the cases to select among,
  8057. inside braces.  It looks like this:
  8058.  
  8059. @example
  8060. switch (@var{selector})
  8061.  @{
  8062.    @var{cases}@r{@dots{}}
  8063.  @}
  8064. @end example
  8065.  
  8066. A case can look like this:
  8067.  
  8068. @example
  8069. case @var{value}:
  8070.  @var{statements}
  8071.  break;
  8072. @end example
  8073.  
  8074. @noindent
  8075. which means ``come here if @var{selector} happens to have the value
  8076. @var{value},'' or like this (a GNU C extension):
  8077.  
  8078. @example
  8079. case @var{rangestart} ... @var{rangeend}:
  8080.  @var{statements}
  8081.  break;
  8082. @end example
  8083.  
  8084. @noindent
  8085. which means ``come here if @var{selector} happens to have a value
  8086. between @var{rangestart} and @var{rangeend} (inclusive).''  @xref{Case
  8087. Ranges}.
  8088.  
  8089. The values in @code{case} labels must reduce to integer constants.
  8090. They can use arithmetic, and @code{enum} constants, but they cannot
  8091. refer to data in memory, because they have to be computed at compile
  8092. time.  It is an error if two @code{case} labels specify the same
  8093. value, or ranges that overlap, or if one is a range and the other is a
  8094. value in that range.
  8095.  
  8096. You can also define a default case to handle ``any other value,'' like
  8097. this:
  8098.  
  8099. @example
  8100. default:
  8101.  @var{statements}
  8102.  break;
  8103. @end example
  8104.  
  8105. If the @code{switch} statement has no @code{default:} label, then it
  8106. does nothing when the value matches none of the cases.
  8107.  
  8108. The brace-group inside the @code{switch} statement is a block, and you
  8109. can declare variables with that scope just as in any other block
  8110. (@pxref{Blocks}).  However, initializers in these declarations won't
  8111. necessarily be executed every time the @code{switch} statement runs,
  8112. so it is best to avoid giving them initializers.
  8113.  
  8114. @code{break;} inside a @code{switch} statement exits immediately from
  8115. the @code{switch} statement.  @xref{break Statement}.
  8116.  
  8117. If there is no @code{break;} at the end of the code for a case,
  8118. execution continues into the code for the following case.  This
  8119. happens more often by mistake than intentionally, but since this
  8120. feature is used in real code, we cannot eliminate it.
  8121.  
  8122. @strong{Warning:} When one case is intended to fall through to the
  8123. next, write a comment like @samp{falls through} to say it's
  8124. intentional.  That way, other programmers won't assume it was an error
  8125. and ``fix'' it erroneously.
  8126.  
  8127. Consecutive @code{case} statements could, pedantically, be considered
  8128. an instance of falling through, but we don't consider or treat them that
  8129. way because they won't confuse anyone.
  8130.  
  8131. @node switch Example
  8132. @section Example of @code{switch}
  8133.  
  8134. Here's an example of using the @code{switch} statement
  8135. to distinguish among characters:
  8136.  
  8137. @cindex counting vowels and punctuation
  8138. @example
  8139. struct vp @{ int vowels, punct; @};
  8140.  
  8141. struct vp
  8142. count_vowels_and_punct (char *string)
  8143. @{
  8144.  int c;
  8145.  int vowels = 0;
  8146.  int punct = 0;
  8147.  /* @r{Don't change the parameter itself.}  */
  8148.  /* @r{That helps in debugging.}  */
  8149.  char *p = string;
  8150.  struct vp value;
  8151.  
  8152.  while (c = *p++)
  8153.    switch (c)
  8154.      @{
  8155.        case 'y':
  8156.        case 'Y':
  8157.          /* @r{We assume @code{y_is_consonant} will check surrounding
  8158.                letters to determine whether this y is a vowel.}  */
  8159.          if (y_is_consonant (p - 1))
  8160.            break;
  8161.  
  8162.          /* @r{Falls through} */
  8163.  
  8164.        case 'a':
  8165.        case 'e':
  8166.        case 'i':
  8167.        case 'o':
  8168.        case 'u':
  8169.        case 'A':
  8170.        case 'E':
  8171.        case 'I':
  8172.        case 'O':
  8173.        case 'U':
  8174.          vowels++;
  8175.          break;
  8176.  
  8177.        case '.':
  8178.        case ',':
  8179.        case ':':
  8180.        case ';':
  8181.        case '?':
  8182.        case '!':
  8183.        case '\"':
  8184.        case '\'':
  8185.          punct++;
  8186.          break;
  8187.      @}
  8188.  
  8189.  value.vowels = vowels;
  8190.  value.punct = punct;
  8191.  
  8192.  return value;
  8193. @}
  8194. @end example
  8195.  
  8196. @node Duffs Device
  8197. @section Duff's Device
  8198. @cindex Duff's device
  8199.  
  8200. The cases in a @code{switch} statement can be inside other control
  8201. constructs.  For instance, we can use a technique known as @dfn{Duff's
  8202. device} to optimize this simple function,
  8203.  
  8204. @example
  8205. void
  8206. copy (char *to, char *from, int count)
  8207. @{
  8208.  while (count > 0)
  8209.    *to++ = *from++, count--;
  8210. @}
  8211. @end example
  8212.  
  8213. @noindent
  8214. which copies memory starting at @var{from} to memory starting at
  8215. @var{to}.
  8216.  
  8217. Duff's device involves unrolling the loop so that it copies
  8218. several characters each time around, and using a @code{switch} statement
  8219. to enter the loop body at the proper point:
  8220.  
  8221. @example
  8222. void
  8223. copy (char *to, char *from, int count)
  8224. @{
  8225.   if (count <= 0)
  8226.     return;
  8227.   int n = (count + 7) / 8;
  8228.   switch (count % 8)
  8229.     @{
  8230.      do @{
  8231.        case 0: *to++ = *from++;
  8232.        case 7: *to++ = *from++;
  8233.        case 6: *to++ = *from++;
  8234.        case 5: *to++ = *from++;
  8235.        case 4: *to++ = *from++;
  8236.        case 3: *to++ = *from++;
  8237.        case 2: *to++ = *from++;
  8238.        case 1: *to++ = *from++;
  8239.        @} while (--n > 0);
  8240.    @}
  8241. @}
  8242. @end example
  8243.  
  8244. @node Case Ranges
  8245. @section Case Ranges
  8246. @cindex case ranges
  8247. @cindex ranges in case statements
  8248.  
  8249. You can specify a range of consecutive values in a single @code{case} label,
  8250. like this:
  8251.  
  8252. @example
  8253. case @var{low} ... @var{high}:
  8254. @end example
  8255.  
  8256. @noindent
  8257. This has the same effect as the proper number of individual @code{case}
  8258. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  8259.  
  8260. This feature is especially useful for ranges of ASCII character codes:
  8261.  
  8262. @example
  8263. case 'A' ... 'Z':
  8264. @end example
  8265.  
  8266. @strong{Be careful:} with integers, write spaces around the @code{...}
  8267. to prevent it from being parsed wrong.  For example, write this:
  8268.  
  8269. @example
  8270. case 1 ... 5:
  8271. @end example
  8272.  
  8273. @noindent
  8274. rather than this:
  8275.  
  8276. @example
  8277. case 1...5:
  8278. @end example
  8279.  
  8280. @node Null Statement
  8281. @section Null Statement
  8282. @cindex null statement
  8283. @cindex statement, null
  8284.  
  8285. A @dfn{null statement} is just a semicolon.  It does nothing.
  8286.  
  8287. A null statement is a placeholder for use where a statement is
  8288. grammatically required, but there is nothing to be done.  For
  8289. instance, sometimes all the work of a @code{for}-loop is done in the
  8290. @code{for}-header itself, leaving no work for the body.  Here is an
  8291. example that searches for the first newline in @code{array}:
  8292.  
  8293. @example
  8294. for (p = array; *p != '\n'; p++)
  8295.  ;
  8296. @end example
  8297.  
  8298. @node goto Statement
  8299. @section @code{goto} Statement and Labels
  8300. @cindex @code{goto} statement
  8301. @cindex statement, @code{goto}
  8302. @cindex label
  8303. @findex goto
  8304.  
  8305. The @code{goto} statement looks like this:
  8306.  
  8307. @example
  8308. goto @var{label};
  8309. @end example
  8310.  
  8311. @noindent
  8312. Its effect is to transfer control immediately to another part of the
  8313. current function---where the label named @var{label} is defined.
  8314.  
  8315. An ordinary label definition looks like this:
  8316.  
  8317. @example
  8318. @var{label}:
  8319. @end example
  8320.  
  8321. @noindent
  8322. and it can appear before any statement.  You can't use @code{default}
  8323. as a label, since that has a special meaning for @code{switch}
  8324. statements.
  8325.  
  8326. An ordinary label doesn't need a separate declaration; defining it is
  8327. enough.
  8328.  
  8329. Here's an example of using @code{goto} to implement a loop
  8330. equivalent to @code{do}--@code{while}:
  8331.  
  8332. @example
  8333. @{
  8334. loop_restart:
  8335.  @var{body}
  8336.  if (@var{condition})
  8337.    goto loop_restart;
  8338. @}
  8339. @end example
  8340.  
  8341. The name space of labels is separate from that of variables and functions.
  8342. Thus, there is no error in using a single name in both ways:
  8343.  
  8344. @example
  8345. @{
  8346.  int foo;    // @r{Variable @code{foo}.}
  8347. foo:         // @r{Label @code{foo}.}
  8348.  @var{body}
  8349.  if (foo > 0)  // @r{Variable @code{foo}.}
  8350.    goto foo;   // @r{Label @code{foo}.}
  8351. @}
  8352. @end example
  8353.  
  8354. Blocks have no effect on ordinary labels; each label name is defined
  8355. throughout the whole of the function it appears in.  It looks strange to
  8356. jump into a block with @code{goto}, but it works.  For example,
  8357.  
  8358. @example
  8359. if (x < 0)
  8360.  goto negative;
  8361. if (y < 0)
  8362.  @{
  8363.   negative:
  8364.    printf ("Negative\n");
  8365.    return;
  8366.  @}
  8367. @end example
  8368.  
  8369. If the goto jumps into the scope of a variable, it does not
  8370. initialize the variable.  For example, if @code{x} is negative,
  8371.  
  8372. @example
  8373. if (x < 0)
  8374.   goto negative;
  8375. if (y < 0)
  8376.   @{
  8377.     int i = 5;
  8378.    negative:
  8379.     printf ("Negative, and i is %d\n", i);
  8380.     return;
  8381.   @}
  8382. @end example
  8383.  
  8384. @noindent
  8385. prints junk because @code{i} was not initialized.
  8386.  
  8387. If the block declares a variable-length automatic array, jumping into
  8388. it gives a compilation error.  However, jumping out of the scope of a
  8389. variable-length array works fine, and deallocates its storage.
  8390.  
  8391. A label can't come directly before a declaration, so the code can't
  8392. jump directly to one.  For example, this is not allowed:
  8393.  
  8394. @example
  8395. @{
  8396.  goto foo;
  8397. foo:
  8398.  int x = 5;
  8399.  bar(&x);
  8400. @}
  8401. @end example
  8402.  
  8403. @noindent
  8404. The workaround is to add a statement, even an empty statement,
  8405. directly after the label.  For example:
  8406.  
  8407. @example
  8408. @{
  8409.  goto foo;
  8410. foo:
  8411.  ;
  8412.  int x = 5;
  8413.  bar(&x);
  8414. @}
  8415. @end example
  8416.  
  8417. Likewise, a label can't be the last thing in a block.  The workaround
  8418. solution is the same: add a semicolon after the label.
  8419.  
  8420. These unnecessary restrictions on labels make no sense, and ought in
  8421. principle to be removed; but they do only a little harm since labels
  8422. and @code{goto} are rarely the best way to write a program.
  8423.  
  8424. These examples are all artificial; it would be more natural to
  8425. write them in other ways, without @code{goto}.  For instance,
  8426. the clean way to write the example that prints @samp{Negative} is this:
  8427.  
  8428. @example
  8429. if (x < 0 || y < 0)
  8430.  @{
  8431.    printf ("Negative\n");
  8432.    return;
  8433.  @}
  8434. @end example
  8435.  
  8436. @noindent
  8437. It is hard to construct simple examples where @code{goto} is actually
  8438. the best way to write a program.  Its rare good uses tend to be in
  8439. complex code, thus not apt for the purpose of explaining the meaning
  8440. of @code{goto}.
  8441.  
  8442. The only good time to use @code{goto} is when it makes the code
  8443. simpler than any alternative.  Jumping backward is rarely desirable,
  8444. because usually the other looping and control constructs give simpler
  8445. code.  Using @code{goto} to jump forward is more often desirable, for
  8446. instance when a function needs to do some processing in an error case
  8447. and errors can occur at various different places within the function.
  8448.  
  8449. @node Local Labels
  8450. @section Locally Declared Labels
  8451. @cindex local labels
  8452. @cindex macros, local labels
  8453. @findex __label__
  8454.  
  8455. In GNU C you can declare @dfn{local labels} in any nested block
  8456. scope.  A local label is used in a @code{goto} statement just like an
  8457. ordinary label, but you can only reference it within the block in
  8458. which it was declared.
  8459.  
  8460. A local label declaration looks like this:
  8461.  
  8462. @example
  8463. __label__ @var{label};
  8464. @end example
  8465.  
  8466. @noindent
  8467. or
  8468.  
  8469. @example
  8470. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  8471. @end example
  8472.  
  8473. Local label declarations must come at the beginning of the block,
  8474. before any ordinary declarations or statements.
  8475.  
  8476. The label declaration declares the label @emph{name}, but does not define
  8477. the label itself.  That's done in the usual way, with
  8478. @code{@var{label}:}, before one of the statements in the block.
  8479.  
  8480. The local label feature is useful for complex macros.  If a macro
  8481. contains nested loops, a @code{goto} can be useful for breaking out of
  8482. them.  However, an ordinary label whose scope is the whole function
  8483. cannot be used: if the macro can be expanded several times in one
  8484. function, the label will be multiply defined in that function.  A
  8485. local label avoids this problem.  For example:
  8486.  
  8487. @example
  8488. #define SEARCH(value, array, target)              \
  8489. do @{                                              \
  8490.  __label__ found;                                \
  8491.  __auto_type _SEARCH_target = (target);          \
  8492.  __auto_type _SEARCH_array = (array);            \
  8493.  int i, j;                                       \
  8494.  int value;                                      \
  8495.  for (i = 0; i < max; i++)                       \
  8496.    for (j = 0; j < max; j++)                     \
  8497.      if (_SEARCH_array[i][j] == _SEARCH_target)  \
  8498.        @{ (value) = i; goto found; @}              \
  8499.  (value) = -1;                                   \
  8500. found:;                                          \
  8501. @} while (0)
  8502. @end example
  8503.  
  8504. This could also be written using a statement expression
  8505. (@pxref{Statement Exprs}):
  8506.  
  8507. @example
  8508. #define SEARCH(array, target)                     \
  8509. (@{                                                \
  8510.  __label__ found;                                \
  8511.  __auto_type _SEARCH_target = (target);      \
  8512.  __auto_type _SEARCH_array = (array);     \
  8513.  int i, j;                                       \
  8514.  int value;                                      \
  8515.  for (i = 0; i < max; i++)                       \
  8516.    for (j = 0; j < max; j++)                     \
  8517.      if (_SEARCH_array[i][j] == _SEARCH_target)  \
  8518.        @{ value = i; goto found; @}                \
  8519.  value = -1;                                     \
  8520. found:                                           \
  8521.  value;                                          \
  8522. @})
  8523. @end example
  8524.  
  8525. Ordinary labels are visible throughout the function where they are
  8526. defined, and only in that function.  However, explicitly declared
  8527. local labels of a block are visible in nested functions declared
  8528. within that block.  @xref{Nested Functions}, for details.
  8529.  
  8530. @xref{goto Statement}.
  8531.  
  8532. @node Labels as Values
  8533. @section Labels as Values
  8534. @cindex labels as values
  8535. @cindex computed gotos
  8536. @cindex goto with computed label
  8537. @cindex address of a label
  8538.  
  8539. In GNU C, you can get the address of a label defined in the current
  8540. function (or a local label defined in the containing function) with
  8541. the unary operator @samp{&&}.  The value has type @code{void *}.  This
  8542. value is a constant and can be used wherever a constant of that type
  8543. is valid.  For example:
  8544.  
  8545. @example
  8546. void *ptr;
  8547. @r{@dots{}}
  8548. ptr = &&foo;
  8549. @end example
  8550.  
  8551. To use these values requires a way to jump to one.  This is done
  8552. with the computed goto statement@footnote{The analogous feature in
  8553. Fortran is called an assigned goto, but that name seems inappropriate in
  8554. C, since you can do more with label addresses than store them in special label
  8555. variables.}, @code{goto *@var{exp};}.  For example,
  8556.  
  8557. @example
  8558. goto *ptr;
  8559. @end example
  8560.  
  8561. @noindent
  8562. Any expression of type @code{void *} is allowed.
  8563.  
  8564. @xref{goto Statement}.
  8565.  
  8566. @menu
  8567. * Label Value Uses::       Examples of using label values.
  8568. * Label Value Caveats::    Limitations of label values.
  8569. @end menu
  8570.  
  8571. @node Label Value Uses
  8572. @subsection Label Value Uses
  8573.  
  8574. One use for label-valued constants is to initialize a static array to
  8575. serve as a jump table:
  8576.  
  8577. @example
  8578. static void *array[] = @{ &&foo, &&bar, &&hack @};
  8579. @end example
  8580. Then you can select a label with indexing, like this:
  8581. @example
  8582. goto *array[i];
  8583. @end example
  8584.  
  8585. @noindent
  8586. Note that this does not check whether the subscript is in bounds---array
  8587. indexing in C never checks that.
  8588.  
  8589. You can make the table entries offsets instead of addresses
  8590. by subtracting one label from the others.  Here is an example:
  8591.  
  8592. @example
  8593. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  8594.                             &&hack - &&foo @};
  8595. goto *(&&foo + array[i]);
  8596. @end example
  8597.  
  8598. @noindent
  8599. Using offsets is preferable in shared libraries, as it avoids the need
  8600. for dynamic relocation of the array elements; therefore, the array can
  8601. be read-only.
  8602.  
  8603. An array of label values or offsets serves a purpose much like that of
  8604. the @code{switch} statement.  The @code{switch} statement is cleaner,
  8605. so use @code{switch} by preference when feasible.
  8606.  
  8607. Another use of label values is in an interpreter for threaded code.
  8608. The labels within the interpreter function can be stored in the
  8609. threaded code for super-fast dispatching.
  8610.  
  8611. @node Label Value Caveats
  8612. @subsection Label Value Caveats
  8613.  
  8614. Jumping to a label defined in another function does not work.
  8615. It can cause unpredictable results.
  8616.  
  8617. The best way to avoid this is to store label values only in
  8618. automatic variables, or static variables whose names are declared
  8619. within the function.  Never pass them as arguments.
  8620.  
  8621. @cindex cloning
  8622. An optimization known as @dfn{cloning} generates multiple simplified
  8623. variants of a function's code, for use with specific fixed arguments.
  8624. Using label values in certain ways, such as saving the address in one
  8625. call to the function and using it again in another call, would make cloning
  8626. give incorrect results.  These functions must disable cloning.
  8627.  
  8628. Inlining calls to the function would also result in multiple copies of
  8629. the code, each with its own value of the same label.  Using the label
  8630. in a computed goto is no problem, because the computed goto inhibits
  8631. inlining.  However, using the label value in some other way, such as
  8632. an indication of where an error occurred, would be optimized wrong.
  8633. These functions must disable inlining.
  8634.  
  8635. To prevent inlining or cloning of a function, specify
  8636. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  8637. @xref{Attributes}.
  8638.  
  8639. When a function uses a label value in a static variable initializer,
  8640. that automatically prevents inlining or cloning the function.
  8641.  
  8642. @node Statement Exprs
  8643. @section Statements and Declarations in Expressions
  8644. @cindex statements inside expressions
  8645. @cindex declarations inside expressions
  8646. @cindex expressions containing statements
  8647.  
  8648. @c the above section title wrapped and causes an underfull hbox.. i
  8649. @c changed it from "within" to "in". --mew 4feb93
  8650. A block enclosed in parentheses can be used as an expression in GNU
  8651. C@.  This provides a way to use local variables, loops and switches within
  8652. an expression.  We call it a @dfn{statement expression}.
  8653.  
  8654. Recall that a block is a sequence of statements
  8655. surrounded by braces.  In this construct, parentheses go around the
  8656. braces.  For example:
  8657.  
  8658. @example
  8659. (@{ int y = foo (); int z;
  8660.   if (y > 0) z = y;
  8661.   else z = - y;
  8662.   z; @})
  8663. @end example
  8664.  
  8665. @noindent
  8666. is a valid (though slightly more complex than necessary) expression
  8667. for the absolute value of @code{foo ()}.
  8668.  
  8669. The last statement in the block should be an expression statement; an
  8670. expression followed by a semicolon, that is.  The value of this
  8671. expression serves as the value of statement expression.  If the last
  8672. statement is anything else, the statement expression's value is
  8673. @code{void}.
  8674.  
  8675. This feature is mainly useful in making macro definitions compute each
  8676. operand exactly once.  @xref{Macros and Auto Type}.
  8677.  
  8678. Statement expressions are not allowed in expressions that must be
  8679. constant, such as the value for an enumerator, the width of a
  8680. bit-field, or the initial value of a static variable.
  8681.  
  8682. Jumping into a statement expression---with @code{goto}, or using a
  8683. @code{switch} statement outside the statement expression---is an
  8684. error.  With a computed @code{goto} (@pxref{Labels as Values}), the
  8685. compiler can't detect the error, but it still won't work.
  8686.  
  8687. Jumping out of a statement expression is permitted, but since
  8688. subexpressions in C are not computed in a strict order, it is
  8689. unpredictable which other subexpressions will have been computed by
  8690. then.  For example,
  8691.  
  8692. @example
  8693.  foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  8694. @end example
  8695.  
  8696. @noindent
  8697. calls @code{foo} and @code{bar1} before it jumps, and never
  8698. calls @code{baz}, but may or may not call @code{bar2}.  If @code{bar2}
  8699. does get called, that occurs after @code{foo} and before @code{bar1}.
  8700.  
  8701. @node Variables
  8702. @chapter Variables
  8703. @cindex variables
  8704.  
  8705. Every variable used in a C program needs to be made known by a
  8706. @dfn{declaration}.  It can be used only after it has been declared.
  8707. It is an error to declare a variable name more than once in the same
  8708. scope; an exception is that @code{extern} declarations and tentative
  8709. definitions can coexist with another declaration of the same
  8710. variable.
  8711.  
  8712. Variables can be declared anywhere within a block or file. (Older
  8713. versions of C required that all variable declarations within a block
  8714. occur before any statements.)
  8715.  
  8716. Variables declared within a function or block are @dfn{local} to
  8717. it.  This means that the variable name is visible only until the end
  8718. of that function or block, and the memory space is allocated only
  8719. while control is within it.
  8720.  
  8721. Variables declared at the top level in a file are called @dfn{file-scope}.
  8722. They are assigned fixed, distinct memory locations, so they retain
  8723. their values for the whole execution of the program.
  8724.  
  8725. @menu
  8726. * Variable Declarations::        Name a variable and and reserve space for it.
  8727. * Initializers::                 Assigning inital values to variables.
  8728. * Designated Inits::             Assigning initial values to array elements
  8729.                                   at particular array indices.
  8730. * Auto Type::                    Obtaining the type of a variable.
  8731. * Local Variables::              Variables declared in function definitions.
  8732. * File-Scope Variables::         Variables declared outside of
  8733.                                   function definitions.
  8734. * Static Local Variables::       Variables declared within functions,
  8735.                                   but with permanent storage allocation.
  8736. * Extern Declarations::          Declaring a variable
  8737.                                   which is allocated somewhere else.
  8738. * Allocating File-Scope::        When is space allocated
  8739.                                   for file-scope variables?
  8740. * auto and register::            Historically used storage directions.
  8741. * Omitting Types::               The bad practice of declaring variables
  8742.                                   with implicit type.
  8743. @end menu
  8744.  
  8745. @node Variable Declarations
  8746. @section Variable Declarations
  8747. @cindex variable declarations
  8748. @cindex declaration of variables
  8749.  
  8750. Here's what a variable declaration looks like:
  8751.  
  8752. @example
  8753. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  8754. @end example
  8755.  
  8756. The @var{keywords} specify how to handle the scope of the variable
  8757. name and the allocation of its storage.  Most declarations have
  8758. no keywords because the defaults are right for them.
  8759.  
  8760. C allows these keywords to come before or after @var{basetype}, or
  8761. even in the middle of it as in @code{unsigned static int}, but don't
  8762. do that---it would surprise other programmers.  Always write the
  8763. keywords first.
  8764.  
  8765. The @var{basetype} can be any of the predefined types of C, or a type
  8766. keyword defined with @code{typedef}.  It can also be @code{struct
  8767. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}.  In
  8768. addition, it can include type qualifiers such as @code{const} and
  8769. @code{volatile} (@pxref{Type Qualifiers}).
  8770.  
  8771. In the simplest case, @var{decorated-variable} is just the variable
  8772. name.  That declares the variable with the type specified by
  8773. @var{basetype}.  For instance,
  8774.  
  8775. @example
  8776. int foo;
  8777. @end example
  8778.  
  8779. @noindent
  8780. uses @code{int} as the @var{basetype} and @code{foo} as the
  8781. @var{decorated-variable}.  It declares @code{foo} with type
  8782. @code{int}.
  8783.  
  8784. @example
  8785. struct tree_node foo;
  8786. @end example
  8787.  
  8788. @noindent
  8789. declares @code{foo} with type @code{struct tree_node}.
  8790.  
  8791. @menu
  8792. * Declaring Arrays and Pointers::   Declaration syntax for variables of
  8793.                                      array and pointer types.
  8794. * Combining Variable Declarations:: More than one variable declaration
  8795.                                      in a single statement.
  8796. @end menu
  8797.  
  8798. @node Declaring Arrays and Pointers
  8799. @subsection Declaring Arrays and Pointers
  8800. @cindex declaring arrays and pointers
  8801. @cindex array, declaring
  8802. @cindex pointers, declaring
  8803.  
  8804. To declare a variable that is an array, write
  8805. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  8806.  
  8807. @example
  8808. int foo[5];
  8809. @end example
  8810.  
  8811. To declare a variable that has a pointer type, write
  8812. @code{*@var{variable}} for @var{decorated-variable}:
  8813.  
  8814. @example
  8815. struct list_elt *foo;
  8816. @end example
  8817.  
  8818. These constructs nest.  For instance,
  8819.  
  8820. @example
  8821. int foo[3][5];
  8822. @end example
  8823.  
  8824. @noindent
  8825. declares @code{foo} as an array of 3 arrays of 5 integers each,
  8826.  
  8827. @example
  8828. struct list_elt *foo[5];
  8829. @end example
  8830.  
  8831. @noindent
  8832. declares @code{foo} as an array of 5 pointers to structures, and
  8833.  
  8834. @example
  8835. struct list_elt **foo;
  8836. @end example
  8837.  
  8838. @noindent
  8839. declares @code{foo} as a pointer to a pointer to a structure.
  8840.  
  8841. @example
  8842. int **(*foo[30])(int, double);
  8843. @end example
  8844.  
  8845. @noindent
  8846. declares @code{foo} as an array of 30 pointers to functions
  8847. (@pxref{Function Pointers}), each of which must accept two arguments
  8848. (one @code{int} and one @code{double}) and return type @code{int **}.
  8849.  
  8850. @example
  8851. void
  8852. bar (int size)
  8853. @{
  8854.  int foo[size];
  8855.  @r{@dots{}}
  8856. @}
  8857. @end example
  8858.  
  8859. @noindent
  8860. declares @code{foo} as an array of integers with a size specified at
  8861. run time when the function @code{bar} is called.
  8862.  
  8863. @node Combining Variable Declarations
  8864. @subsection Combining Variable Declarations
  8865. @cindex combining variable declarations
  8866. @cindex variable declarations, combining
  8867. @cindex declarations, combining
  8868.  
  8869. When multiple declarations have the same @var{keywords} and
  8870. @var{basetype}, you can combine them using commas.  Thus,
  8871.  
  8872. @example
  8873. @var{keywords} @var{basetype}
  8874.   @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  8875.   @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  8876. @end example
  8877.  
  8878. @noindent
  8879. is equivalent to
  8880.  
  8881. @example
  8882. @var{keywords} @var{basetype}
  8883.   @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  8884. @var{keywords} @var{basetype}
  8885.   @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  8886. @end example
  8887.  
  8888. Here are some simple examples:
  8889.  
  8890. @example
  8891. int a, b;
  8892. int a = 1, b = 2;
  8893. int a, *p, array[5];
  8894. int a = 0, *p = &a, array[5] = @{1, 2@};
  8895. @end example
  8896.  
  8897. @noindent
  8898. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  8899. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  8900. Since the initializer for @code{array} specifies only two elements,
  8901. the other three elements are initialized to zero.
  8902.  
  8903. @node Initializers
  8904. @section Initializers
  8905. @cindex initializers
  8906.  
  8907. A variable's declaration, unless it is @code{extern}, should also
  8908. specify its initial value.  For numeric and pointer-type variables,
  8909. the initializer is an expression for the value.  If necessary, it is
  8910. converted to the variable's type, just as in an assignment.
  8911.  
  8912. You can also initialize a local structure-type (@pxref{Structures}) or
  8913. local union-type (@pxref{Unions}) variable this way, from an
  8914. expression whose value has the same type.  But you can't initialize an
  8915. array this way (@pxref{Arrays}), since arrays are not first-class
  8916. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  8917. assignment.
  8918.  
  8919. You can initialize arrays and structures componentwise,
  8920. with a list of the elements or components.  You can initialize
  8921. a union with any one of its alternatives.
  8922.  
  8923. @itemize @bullet
  8924. @item
  8925. A component-wise initializer for an array consists of element values
  8926. surrounded by @samp{@{@r{@dots{}}@}}.  If the values in the initializer
  8927. don't cover all the elements in the array, the remaining elements are
  8928. initialized to zero.
  8929.  
  8930. You can omit the size of the array when you declare it, and let
  8931. the initializer specify the size:
  8932.  
  8933. @example
  8934. int array[] = @{ 3, 9, 12 @};
  8935. @end example
  8936. @item
  8937. A component-wise initializer for a structure consists of field values
  8938. surrounded by @samp{@{@r{@dots{}}@}}.  Write the field values in the same
  8939. order as the fields are declared in the structure.  If the values in
  8940. the initializer don't cover all the fields in the structure, the
  8941. remaining fields are initialized to zero.
  8942. @item
  8943. The initializer for a union-type variable has the form @code{@{
  8944. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  8945. in the union definition.
  8946. @end itemize
  8947. For an array of arrays, a structure containing arrays, an array of
  8948. structures, etc., you can nest these constructs.  For example,
  8949. @example
  8950. struct point @{ double x, y; @};
  8951. struct point series[]
  8952.  = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  8953. @end example
  8954. You can omit a pair of inner braces if they contain the right
  8955. number of elements for the sub-value they initialize, so that
  8956. no elements or fields need to be filled in with zeros.
  8957. But don't do that very much, as it gets confusing.
  8958. An array of @code{char} can be initialized using a string constant.
  8959. Recall that the string constant includes an implicit null character at
  8960. the end (@pxref{String Constants}).  Using a string constant as
  8961. initializer means to use its contents as the initial values of the
  8962. array elements.  Here are examples:
  8963. @example
  8964. char text[6] = "text!";     /* @r{Includes the null.} */
  8965. char text[5] = "text!";     /* @r{Excludes the null.} */
  8966. char text[] = "text!";      /* @r{Gets length 6.} */
  8967. char text[]
  8968.  = @{ 't', 'e', 'x', 't', '!', 0 @};  /* @r{same as above.} */
  8969. char text[] = @{ "text!" @};  /* @r{Braces are optional.} */
  8970. @end example
  8971. @noindent
  8972. and this kind of initializer can be nested inside braces to initialize
  8973. structures or arrays that contain a @code{char}-array.
  8974. In like manner, you can use a wide string constant to initialize
  8975. an array of @code{wchar_t}.
  8976. @node Designated Inits
  8977. @section Designated Initializers
  8978. @cindex initializers with labeled elements
  8979. @cindex labeled elements in initializers
  8980. @cindex case labels in initializers
  8981. @cindex designated initializers
  8982. In a complex structure or long array, it's useful to indicate
  8983. which field or element we are initializing.
  8984. To designate specific array elements during initialization, include
  8985. the array index in brackets, and an assignment operator, for each
  8986. element:
  8987. @example
  8988. int foo[10] = @{ [3] = 42, [7] = 58 @};
  8989. @end example
  8990.  
  8991. @noindent
  8992. This does the same thing as:
  8993.  
  8994. @example
  8995. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  8996. @end example
  8997.  
  8998. The array initialization can include non-designated element values
  8999. alongside designated indices; these follow the expected ordering
  9000. of the array initialization, so that
  9001.  
  9002. @example
  9003. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  9004. @end example
  9005.  
  9006. @noindent
  9007. does the same thing as:
  9008.  
  9009. @example
  9010. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  9011. @end example
  9012.  
  9013. Note that you can only use constant expressions as array index values,
  9014. not variables.
  9015.  
  9016. If you need to initialize a subsequence of sequential array elements to
  9017. the same value, you can specify a range:
  9018.  
  9019. @example
  9020. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  9021. @end example
  9022.  
  9023. @noindent
  9024. Using a range this way is a GNU C extension.
  9025.  
  9026. When subsequence ranges overlap, each element is initialized by the
  9027. last specification that applies to it.  Thus, this initialization is
  9028. equivalent to the previous one.
  9029.  
  9030. @example
  9031. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  9032. @end example
  9033.  
  9034. @noindent
  9035. as the second overrides the first for elements 0 through 19.
  9036.  
  9037. The value used to initialize a range of elements is evaluated only
  9038. once, for the first element in the range.  So for example, this code
  9039.  
  9040. @example
  9041. int random_values[100]
  9042.  = @{ [0 ... 99] = get_random_number() @};
  9043. @end example
  9044.  
  9045. @noindent
  9046. would initialize all 100 elements of the array @code{random_values} to
  9047. the same value---probably not what is intended.
  9048.  
  9049. Similarly, you can initialize specific fields of a structure variable
  9050. by specifying the field name prefixed with a dot:
  9051.  
  9052. @example
  9053. struct point @{ int x; int y; @};
  9054.  
  9055. struct point foo = @{ .y = 42; @};
  9056. @end example
  9057.  
  9058. @noindent
  9059. The same syntax works for union variables as well:
  9060.  
  9061. @example
  9062. union int_double @{ int i; double d; @};
  9063.  
  9064. union int_double foo = @{ .d = 34 @};
  9065. @end example
  9066.  
  9067. @noindent
  9068. This casts the integer value 34 to a double and stores it
  9069. in the union variable @code{foo}.
  9070.  
  9071. You can designate both array elements and structure elements in
  9072. the same initialization; for example, here's an array of point
  9073. structures:
  9074.  
  9075. @example
  9076. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  9077. @end example
  9078.  
  9079. Along with the capability to specify particular array and structure
  9080. elements to initialize comes the possibility of initializing the same
  9081. element more than once:
  9082.  
  9083. @example
  9084. int foo[10] = @{ [4] = 42, [4] = 98 @};
  9085. @end example
  9086.  
  9087. @noindent
  9088. In such a case, the last initialization value is retained.
  9089.  
  9090. @node Auto Type
  9091. @section Referring to a Type with @code{__auto_type}
  9092. @findex __auto_type
  9093. @findex typeof
  9094. @cindex macros, types of arguments
  9095.  
  9096. You can declare a variable copying the type from
  9097. the initializer by using @code{__auto_type} instead of a particular type.
  9098. Here's an example:
  9099.  
  9100. @example
  9101. #define max(a,b) \
  9102.  (@{ __auto_type _a = (a); \
  9103.      __auto_type _b = (b); \
  9104.    _a > _b ? _a : _b @})
  9105. @end example
  9106.  
  9107. This defines @code{_a} to be of the same type as @code{a}, and
  9108. @code{_b} to be of the same type as @code{b}.  This is a useful thing
  9109. to do in a macro that ought to be able to handle any type of data
  9110. (@pxref{Macros and Auto Type}).
  9111.  
  9112. The original GNU C method for obtaining the type of a value is to use
  9113. @code{typeof}, which takes as an argument either a value or the name of
  9114. a type.  The previous example could also be written as:
  9115.  
  9116. @example
  9117. #define max(a,b) \
  9118.  (@{ typeof(a) _a = (a); \
  9119.      typeof(b) _b = (b); \
  9120.    _a > _b ? _a : _b @})
  9121. @end example
  9122.  
  9123. @code{typeof} is more flexible than @code{__auto_type}; however, the
  9124. principal use case for @code{typeof} is in variable declarations with
  9125. initialization, which is exactly what @code{__auto_type} handles.
  9126.  
  9127. @node Local Variables
  9128. @section Local Variables
  9129. @cindex local variables
  9130. @cindex variables, local
  9131.  
  9132. Declaring a variable inside a function definition (@pxref{Function
  9133. Definitions}) makes the variable name @dfn{local} to the containing
  9134. block---that is, the containing pair of braces.  More precisely, the
  9135. variable's name is visible starting just after where it appears in the
  9136. declaration, and its visibility continues until the end of the block.
  9137.  
  9138. Local variables in C are generally @dfn{automatic} variables: each
  9139. variable's storage exists only from the declaration to the end of the
  9140. block.  Execution of the declaration allocates the storage, computes
  9141. the initial value, and stores it in the variable.  The end of the
  9142. block deallocates the storage.@footnote{Due to compiler optimizations,
  9143. allocation and deallocation don't necessarily really happen at
  9144. those times.}
  9145.  
  9146. @strong{Warning:} Two declarations for the same local variable
  9147. in the same scope are an error.
  9148.  
  9149. @strong{Warning:} Automatic variables are stored in the run-time stack.
  9150. The total space for the program's stack may be limited; therefore,
  9151. in using very large arrays, it may be necessary to allocate
  9152. them in some other way to stop the program from crashing.
  9153.  
  9154. @strong{Warning:} If the declaration of an automatic variable does not
  9155. specify an initial value, the variable starts out containing garbage.
  9156. In this example, the value printed could be anything at all:
  9157.  
  9158. @example
  9159. @{
  9160.   int i;
  9161.  
  9162.   printf ("Print junk %d\n", i);
  9163. @}
  9164. @end example
  9165.  
  9166. In a simple test program, that statement is likely to print 0, simply
  9167. because every process starts with memory zeroed.  But don't rely on it
  9168. to be zero---that is erroneous.
  9169.  
  9170. @strong{Note:} Make sure to store a value into each local variable (by
  9171. assignment, or by initialization) before referring to its value.
  9172.  
  9173. @node File-Scope Variables
  9174. @section File-Scope Variables
  9175. @cindex file-scope variables
  9176. @cindex global variables
  9177. @cindex variables, file-scope
  9178. @cindex variables, global
  9179.  
  9180. A variable declaration at the top level in a file (not inside a
  9181. function definition) declares a @dfn{file-scope variable}.  Loading a
  9182. program allocates the storage for all the file-scope variables in it,
  9183. and initializes them too.
  9184.  
  9185. Each file-scope variable is either @dfn{static} (limited to one
  9186. compilation module) or @dfn{global} (shared with all compilation
  9187. modules in the program).  To make the variable static, write the
  9188. keyword @code{static} at the start of the declaration.  Omitting
  9189. @code{static} makes the variable global.
  9190.  
  9191. The initial value for a file-scope variable can't depend on the
  9192. contents of storage, and can't call any functions.
  9193.  
  9194. @example
  9195. int foo = 5;         /* @r{Valid.} */
  9196. int bar = foo;       /* @r{Invalid!} */
  9197. int bar = sin (1.0); /* @r{Invalid!} */
  9198. @end example
  9199.  
  9200. But it can use the address of another file-scope variable:
  9201.  
  9202. @example
  9203. int foo;
  9204. int *bar = &foo;     /* @r{Valid.} */
  9205. int arr[5];
  9206. int *bar3 = &arr[3]; /* @r{Valid.} */
  9207. int *bar4 = arr + 4; /* @r{Valid.} */
  9208. @end example
  9209.  
  9210. It is valid for a module to have multiple declarations for a
  9211. file-scope variable, as long as they are all global or all static, but
  9212. at most one declaration can specify an initial value for it.
  9213.  
  9214. @node Static Local Variables
  9215. @section Static Local Variables
  9216. @cindex static local variables
  9217. @cindex variables, static local
  9218. @findex static
  9219.  
  9220. The keyword @code{static} in a local variable declaration says to
  9221. allocate the storage for the variable permanently, just like a
  9222. file-scope variable, even if the declaration is within a function.
  9223.  
  9224. Here's an example:
  9225.  
  9226. @example
  9227. int
  9228. increment_counter ()
  9229. @{
  9230.  static int counter = 0;
  9231.  return ++counter;
  9232. @}
  9233. @end example
  9234.  
  9235. The scope of the name @code{counter} runs from the declaration to the
  9236. end of the containing block, just like an automatic local variable,
  9237. but its storage is permanent, so the value persists from one call to
  9238. the next.  As a result, each call to @code{increment_counter}
  9239. returns a different, unique value.
  9240.  
  9241. The initial value of a static local variable has the same limitations
  9242. as for file-scope variables: it can't depend on the contents of
  9243. storage or call any functions.  It can use the address of a file-scope
  9244. variable or a static local variable, because those addresses are
  9245. determined before the program runs.
  9246.  
  9247. @node Extern Declarations
  9248. @section @code{extern} Declarations
  9249. @cindex @code{extern} declarations
  9250. @cindex declarations, @code{extern}
  9251. @findex extern
  9252.  
  9253. An @code{extern} declaration is used to refer to a global variable
  9254. whose principal declaration comes elsewhere---in the same module, or in
  9255. another compilation module.  It looks like this:
  9256.  
  9257. @example
  9258. extern @var{basetype} @var{decorated-variable};
  9259. @end example
  9260.  
  9261. Its meaning is that, in the current scope, the variable name refers to
  9262. the file-scope variable of that name---which needs to be declared in a
  9263. non-@code{extern}, non-@code{static} way somewhere else.
  9264.  
  9265. For instance, if one compilation module has this global variable
  9266. declaration
  9267.  
  9268. @example
  9269. int error_count = 0;
  9270. @end example
  9271.  
  9272. @noindent
  9273. then other compilation modules can specify this
  9274.  
  9275. @example
  9276. extern int error_count;
  9277. @end example
  9278.  
  9279. @noindent
  9280. to allow reference to the same variable.
  9281.  
  9282. The usual place to write an @code{extern} declaration is at top level
  9283. in a source file, but you can write an @code{extern} declaration
  9284. inside a block to make a global or static file-scope variable
  9285. accessible in that block.
  9286.  
  9287. Since an @code{extern} declaration does not allocate space for the
  9288. variable, it can omit the size of an array:
  9289.  
  9290. @example
  9291. extern int array[];
  9292. @end example
  9293. You can use @code{array} normally in all contexts where it is
  9294. converted automatically to a pointer.  However, to use it as the
  9295. operand of @code{sizeof} is an error, since the size is unknown.
  9296. It is valid to have multiple @code{extern} declarations for the same
  9297. variable, even in the same scope, if they give the same type.  They do
  9298. not conflict---they agree.  For an array, it is legitimate for some
  9299. @code{extern} declarations can specify the size while others omit it.
  9300. However, if two declarations give different sizes, that is an error.
  9301. Likewise, you can use @code{extern} declarations at file scope
  9302. (@pxref{File-Scope Variables}) followed by an ordinary global
  9303. (non-static) declaration of the same variable.  They do not conflict,
  9304. because they say compatible things about the same meaning of the variable.
  9305. @node Allocating File-Scope
  9306. @section Allocating File-Scope Variables
  9307. @cindex allocation file-scope variables
  9308. @cindex file-scope variables, allocating
  9309. Some file-scope declarations allocate space for the variable, and some
  9310. don't.
  9311. A file-scope declaration with an initial value @emph{must} allocate
  9312. space for the variable; if there are two of such declarations for the
  9313. same variable, even in different compilation modules, they conflict.
  9314. An @code{extern} declaration @emph{never} allocates space for the variable.
  9315. If all the top-level declarations of a certain variable are
  9316. @code{extern}, the variable never gets memory space.  If that variable
  9317. is used anywhere in the program, the use will be reported as an error,
  9318. saying that the variable is not defined.
  9319. @cindex tentative definition
  9320. A file-scope declaration without an initial value is called a
  9321. @dfn{tentative definition}.  This is a strange hybrid: it @emph{can}
  9322. allocate space for the variable, but does not insist.  So it causes no
  9323. conflict, no error, if the variable has another declaration that
  9324. allocates space for it, perhaps in another compilation module.  But if
  9325. nothing else allocates space for the variable, the tentative
  9326. definition will do it.  Any number of compilation modules can declare
  9327. the same variable in this way, and that is sufficient for all of them
  9328. to use the variable.
  9329. @c @opindex -fno-common
  9330. @c @opindex --warn_common
  9331. In programs that are very large or have many contributors, it may be
  9332. wise to adopt the convention of never using tentative definitions.
  9333. You can use the compilation option @option{-fno-common} to make them
  9334. an error, or @option{--warn-common} to warn about them.
  9335. If a file-scope variable gets its space through a tentative
  9336. definition, it starts out containing all zeros.
  9337. @node auto and register
  9338. @section @code{auto} and @code{register}
  9339. @cindex @code{auto} declarations
  9340. @cindex @code{register} declarations
  9341. @findex auto
  9342. @findex register
  9343. For historical reasons, you can write @code{auto} or @code{register}
  9344. before a local variable declaration.  @code{auto} merely emphasizes
  9345. that the variable isn't static; it changes nothing.
  9346. @code{register} suggests to the compiler storing this variable in a
  9347. register.  However, GNU C ignores this suggestion, since it can
  9348. choose the best variables to store in registers without any hints.
  9349. It is an error to take the address of a variable declared
  9350. @code{register}, so you cannot use the unary @samp{&} operator on it.
  9351. If the variable is an array, you can't use it at all (other than as
  9352. the operand of @code{sizeof}), which makes it rather useless.
  9353. @node Omitting Types
  9354. @section Omitting Types in Declarations
  9355. @cindex omitting types in declarations
  9356. The syntax of C traditionally allows omitting the data type in a
  9357. declaration if it specifies a storage class, a type qualifier (see the
  9358. next chapter), or @code{auto} or @code{register}.  Then the type
  9359. defaults to @code{int}.  For example:
  9360. @example
  9361. auto foo = 42;
  9362. @end example
  9363. This is bad practice; if you see it, fix it.
  9364. @node Type Qualifiers
  9365. @chapter Type Qualifiers
  9366. A declaration can include type qualifiers to advise the compiler
  9367. about how the variable will be used.  There are three different
  9368. qualifiers, @code{const}, @code{volatile} and @code{restrict}.  They
  9369. pertain to different issues, so you can use more than one together.
  9370. For instance, @code{const volatile} describes a value that the
  9371. program is not allowed to change, but might have a different value
  9372. each time the program examines it.  (This might perhaps be a special
  9373. hardware register, or part of shared memory.)
  9374. If you are just learning C, you can skip this chapter.
  9375. @menu
  9376. * const::                        Variables whose values don't change.
  9377. * volatile::                     Variables whose values may be accessed
  9378.                                   or changed outside of the control of
  9379.                                   this program.
  9380. * restrict Pointers::            Restricted pointers for code optimization.
  9381. * restrict Pointer Example::     Example of how that works.
  9382. @end menu
  9383. @node const
  9384. @section @code{const} Variables and Fields
  9385. @cindex @code{const} variables and fields
  9386. @cindex variables, @code{const}
  9387. @findex const
  9388. You can mark a variable as ``constant'' by writing @code{const} in
  9389. front of the declaration.  This says to treat any assignment to that
  9390. variable as an error.  It may also permit some compiler
  9391. optimizations---for instance, to fetch the value only once to satisfy
  9392. multiple references to it.  The construct looks like this:
  9393. @example
  9394. const double pi = 3.14159;
  9395. @end example
  9396. After this definition, the code can use the variable @code{pi}
  9397. but cannot assign a different value to it.
  9398. @example
  9399. pi = 3.0; /* @r{Error!} */
  9400. @end example
  9401. Simple variables that are constant can be used for the same purposes
  9402. as enumeration constants, and they are not limited to integers.  The
  9403. constantness of the variable propagates into pointers, too.
  9404. A pointer type can specify that the @emph{target} is constant.  For
  9405. example, the pointer type @code{const double *} stands for a pointer
  9406. to a constant @code{double}.  That's the typethat results from taking
  9407. the address of @code{pi}.  Such a pointer can't be dereferenced in the
  9408. left side of an assignment.
  9409. @example
  9410. *(&pi) = 3.0; /* @r{Error!} */
  9411. @end example
  9412. Nonconstant pointers can be converted automatically to constant
  9413. pointers, but not vice versa.  For instance,
  9414. @example
  9415. const double *cptr;
  9416. double *ptr;
  9417. cptr = &pi;    /* @r{Valid.} */
  9418. cptr = ptr;    /* @r{Valid.} */
  9419. ptr = cptr;    /* @r{Error!} */
  9420. ptr = &pi;     /* @r{Error!} */
  9421. @end example
  9422. This is not an ironclad protection against modifying the value.  You
  9423. can always cast the constant pointer to a nonconstant pointer type:
  9424. @example
  9425. ptr = (double *)cptr;    /* @r{Valid.} */
  9426. ptr = (double *)&pi;     /* @r{Valid.} */
  9427. @end example
  9428. However, @code{const} provides a way to show that a certain function
  9429. won't modify the data structure whose address is passed to it.  Here's
  9430. an example:
  9431. @example
  9432. int
  9433. string_length (const char *string)
  9434. @{
  9435.  int count = 0;
  9436.  while (*string++)
  9437.    count++;
  9438.  return count;
  9439. @}
  9440. @end example
  9441. @noindent
  9442. Using @code{const char *} for the parameter is a way of saying this
  9443. function never modifies the memory of the string itself.
  9444. In calling @code{string_length}, you can specify an ordinary
  9445. @code{char *} since that can be converted automatically to @code{const
  9446. char *}.
  9447. @node volatile
  9448. @section @code{volatile} Variables and Fields
  9449. @cindex @code{volatile} variables and fields
  9450. @cindex variables, @code{volatile}
  9451. @findex volatile
  9452. The GNU C compiler often performs optimizations that eliminate the
  9453. need to write or read a variable.  For instance,
  9454. @example
  9455. int foo;
  9456. foo = 1;
  9457. foo++;
  9458. @end example
  9459. @noindent
  9460. might simply store the value 2 into @code{foo}, without ever storing 1.
  9461. These optimizations can also apply to structure fields in some cases.
  9462. If the memory containing @code{foo} is shared with another program,
  9463. or if it is examined asynchronously by hardware, such optimizations
  9464. could confuse the communication.  Using @code{volatile} is one way
  9465. to prevent them.
  9466. Writing @code{volatile} with the type in a variable or field declaration
  9467. says that the value may be examined or changed for reasons outside the
  9468. control of the program at any moment.  Therefore, the program must
  9469. execute in a careful way to assure correct interaction with those
  9470. accesses, whenever they may occur.
  9471. The simplest use looks like this:
  9472. @example
  9473. volatile int lock;
  9474. @end example
  9475. This directs the compiler not to do certain common optimizations on
  9476. use of the variable @code{lock}.  All the reads and writes for a volatile
  9477. variable or field are really done, and done in the order specified
  9478. by the source code.  Thus, this code:
  9479. @example
  9480. lock = 1;
  9481. list = list->next;
  9482. if (lock)
  9483.  lock_broken (&lock);
  9484. lock = 0;
  9485. @end example
  9486. @noindent
  9487. really stores the value 1 in @code{lock}, even though there is no
  9488. sign it is really used, and the @code{if} statement reads and
  9489. checks the value of @code{lock}, rather than assuming it is still 1.
  9490. A limited amount of optimization can be done, in principle, on
  9491. @code{volatile} variables and fields: multiple references between two
  9492. sequence points (@pxref{Sequence Points}) can be simplified together.
  9493. Use of @code{volatile} does not eliminate the flexibility in ordering
  9494. the computation of the operands of most operators.  For instance, in
  9495. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  9496. @code{foo} is not specified, so they may be done in either order; the
  9497. fact that @code{lock} is @code{volatile} has no effect on that.
  9498. @node restrict Pointers
  9499. @section @code{restrict}-Qualified Pointers
  9500. @cindex @code{restrict} pointers
  9501. @cindex pointers, @code{restrict}-qualified
  9502. @findex restrict
  9503. You can declare a pointer as ``restricted'' using the @code{restrict}
  9504. type qualifier, like this:
  9505. @example
  9506. int *restrict p = x;
  9507. @end example
  9508. @noindent
  9509. This enables better optimization of code that uses the pointer.
  9510. If @code{p} is declared with @code{restrict}, and then the code
  9511. references the object that @code{p} points to (using @code{*p} or
  9512. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  9513. code will not access that object in any other way---only through
  9514. @code{p}.
  9515.  
  9516. For instance, it means the code must not use another pointer
  9517. to access the same space, as shown here:
  9518.  
  9519. @example
  9520. int *restrict p = @var{whatever};
  9521. int *q = p;
  9522. foo (*p, *q);
  9523. @end example
  9524.  
  9525. @noindent
  9526. That contradicts the @code{restrict} promise by accessing the object
  9527. that @code{p} points to using @code{q}, which bypasses @code{p}.
  9528. Likewise, it must not do this:
  9529.  
  9530. @example
  9531. int *restrict p = @var{whatever};
  9532. struct @{ int *a, *b; @} s;
  9533. s.a = p;
  9534. foo (*p, *s.a);
  9535. @end example
  9536.  
  9537. @noindent
  9538. This example uses a structure field instead of the variable @code{q}
  9539. to hold the other pointer, and that contradicts the promise just the
  9540. same.
  9541.  
  9542. The keyword @code{restrict} also promises that @code{p} won't point to
  9543. the allocated space of any automatic or static variable.  So the code
  9544. must not do this:
  9545.  
  9546. @example
  9547. int a;
  9548. int *restrict p = &a;
  9549. foo (*p, a);
  9550. @end example
  9551.  
  9552. @noindent
  9553. because that does direct access to the object (@code{a}) that @code{p}
  9554. points to, which bypasses @code{p}.
  9555.  
  9556. If the code makes such promises with @code{restrict} then breaks them,
  9557. execution is unpredictable.
  9558.  
  9559. @node restrict Pointer Example
  9560. @section @code{restrict} Pointer Example
  9561.  
  9562. Here are examples where @code{restrict} enables real optimization.
  9563.  
  9564. In this example, @code{restrict} assures GCC that the array @code{out}
  9565. points to does not overlap with the array @code{in} points to.
  9566.  
  9567. @example
  9568. void
  9569. process_data (const char *in,
  9570.              char * restrict out,
  9571.              size_t size)
  9572. @{
  9573.  for (i = 0; i < size; i++)
  9574.    out[i] = in[i] + in[i + 1];
  9575. @}
  9576. @end example
  9577.  
  9578. Here's a simple tree structure, where each tree node holds data of
  9579. type @code{PAYLOAD} plus two subtrees.
  9580.  
  9581. @example
  9582. struct foo
  9583.  @{
  9584.    PAYLOAD payload;
  9585.    struct foo *left;
  9586.    struct foo *right;
  9587.  @};
  9588. @end example
  9589.  
  9590. Now here's a function to null out both pointers in the @code{left}
  9591. subtree.
  9592.  
  9593. @example
  9594. void
  9595. null_left (struct foo *a)
  9596. @{
  9597.  a->left->left = NULL;
  9598.  a->left->right = NULL;
  9599. @}
  9600. @end example
  9601.  
  9602. Since @code{*a} and @code{*a->left} have the same data type,
  9603. they could legitimately alias (@pxref{Aliasing}).  Therefore,
  9604. the compiled code for @code{null_left} must read @code{a->left}
  9605. again from memory when executing the second assignment statement.
  9606.  
  9607. We can enable optimization, so that it does not need to read
  9608. @code{a->left} again, by writing @code{null_left} this in a less
  9609. obvious way.
  9610.  
  9611. @example
  9612. void
  9613. null_left (struct foo *a)
  9614. @{
  9615.  struct foo *b = a->left;
  9616.  b->left = NULL;
  9617.  b->right = NULL;
  9618. @}
  9619. @end example
  9620.  
  9621. A more elegant way to fix this is with @code{restrict}.
  9622.  
  9623. @example
  9624. void
  9625. null_left (struct foo *restrict a)
  9626. @{
  9627.  a->left->left = NULL;
  9628.  a->left->right = NULL;
  9629. @}
  9630. @end example
  9631.  
  9632. Declaring @code{a} as @code{restrict} asserts that other pointers such
  9633. as @code{a->left} will not point to the same memory space as @code{a}.
  9634. Therefore, the memory location @code{a->left->left} cannot be the same
  9635. memory as @code{a->left}.  Knowing this, the compiled code may avoid
  9636. reloading @code{a->left} for the second statement.
  9637.  
  9638. @node Functions
  9639. @chapter Functions
  9640. @cindex functions
  9641.  
  9642. We have already presented many examples of functions, so if you've
  9643. read this far, you basically understand the concept of a function.  It
  9644. is vital, nonetheless, to have a chapter in the manual that collects
  9645. all the information about functions.
  9646.  
  9647. @menu
  9648. * Function Definitions::         Writing the body of a function.
  9649. * Function Declarations::        Declaring the interface of a function.
  9650. * Function Calls::               Using functions.
  9651. * Function Call Semantics::      Call-by-value argument passing.
  9652. * Function Pointers::            Using references to functions.
  9653. * The main Function::            Where execution of a GNU C program begins.
  9654. * Advanced Definitions::         Advanced features of function definitions.
  9655. * Obsolete Definitions::         Obsolete features still used
  9656.                                   in function definitions in old code.
  9657. @end menu
  9658.  
  9659. @node Function Definitions
  9660. @section Function Definitions
  9661. @cindex function definitions
  9662. @cindex defining functions
  9663.  
  9664. We have already presented many examples of function definitions.  To
  9665. summarize the rules, a function definition looks like this:
  9666.  
  9667. @example
  9668. @var{returntype}
  9669. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  9670. @{
  9671.  @var{body}
  9672. @}
  9673. @end example
  9674.  
  9675. The part before the open-brace is called the @dfn{function header}.
  9676.  
  9677. Write @code{void} as the @var{returntype} if the function does
  9678. not return a value.
  9679.  
  9680. @menu
  9681. * Function Parameter Variables::     Syntax and semantics
  9682.                                       of function parameters.
  9683. * Forward Function Declarations::    Functions can only be called after
  9684.                                       they have been defined or declared.
  9685. * Static Functions::                 Limiting visibility of a function.
  9686. * Arrays as Parameters::             Functions that accept array arguments.
  9687. * Structs as Parameters::            Functions that accept structure arguments.
  9688. @end menu
  9689.  
  9690. @node Function Parameter Variables
  9691. @subsection Function Parameter Variables
  9692. @cindex function parameter variables
  9693. @cindex parameter variables in functions
  9694. @cindex parameter list
  9695.  
  9696. A function parameter variable is a local variable (@pxref{Local
  9697. Variables}) used within the function to store the value passed as an
  9698. argument in a call to the function.  Usually we say ``function
  9699. parameter'' or ``parameter'' for short, not mentioning the fact that
  9700. it's a variable.
  9701.  
  9702. We declare these variables in the beginning of the function
  9703. definition, in the @dfn{parameter list}.  For example,
  9704.  
  9705. @example
  9706. fib (int n)
  9707. @end example
  9708.  
  9709. @noindent
  9710. has a parameter list with one function parameter @code{n}, which has
  9711. type @code{int}.
  9712.  
  9713. Function parameter declarations differ from ordinary variable
  9714. declarations in several ways:
  9715.  
  9716. @itemize @bullet
  9717. @item
  9718. Inside the function definition header, commas separate parameter
  9719. declarations, and each parameter needs a complete declaration
  9720. including the type.  For instance, if a function @code{foo} has two
  9721. @code{int} parameters, write this:
  9722.  
  9723. @example
  9724. foo (int a, int b)
  9725. @end example
  9726.  
  9727. You can't share the common @code{int} between the two declarations:
  9728.  
  9729. @example
  9730. foo (int a, b)      /* @r{Invalid!} */
  9731. @end example
  9732.  
  9733. @item
  9734. A function parameter variable is initialized to whatever value is
  9735. passed in the function call, so its declaration cannot specify an
  9736. initial value.
  9737.  
  9738. @item
  9739. Writing an array type in a function parameter declaration has the
  9740. effect of declaring it as a pointer.  The size specified for the array
  9741. has no effect at all, and we normally omit the size.  Thus,
  9742.  
  9743. @example
  9744. foo (int a[5])
  9745. foo (int a[])
  9746. foo (int *a)
  9747. @end example
  9748. @noindent
  9749. are equivalent.
  9750. @item
  9751. The scope of the parameter variables is the entire function body,
  9752. notwithstanding the fact that they are written in the function header,
  9753. which is just outside the function body.
  9754. @end itemize
  9755. If a function has no parameters, it would be most natural for the
  9756. list of parameters in its definition to be empty.  But that, in C, has
  9757. a special meaning for historical reasons: ``Do not check that calls to
  9758. this function have the right number of arguments.''  Thus,
  9759. @example
  9760. int
  9761. foo ()
  9762. @{
  9763.  return 5;
  9764. @}
  9765. int
  9766. bar (int x)
  9767. @{
  9768.  return foo (x);
  9769. @}
  9770. @end example
  9771. @noindent
  9772. would not report a compilation error in passing @code{x} as an
  9773. argument to @code{foo}.  By contrast,
  9774. @example
  9775. int
  9776. foo (void)
  9777. @{
  9778.  return 5;
  9779. @}
  9780. int
  9781. bar (int x)
  9782. @{
  9783.  return foo (x);
  9784. @}
  9785. @end example
  9786. @noindent
  9787. would report an error because @code{foo} is supposed to receive
  9788. no arguments.
  9789. @node Forward Function Declarations
  9790. @subsection Forward Function Declarations
  9791. @cindex forward function declarations
  9792. @cindex function declarations, forward
  9793. The order of the function definitions in the source code makes no
  9794. difference, except that each function needs to be defined or declared
  9795. before code uses it.
  9796. The definition of a function also declares its name for the rest of
  9797. the containing scope.  But what if you want to call the function
  9798. before its definition?  To permit that, write a compatible declaration
  9799. of the same function, before the first call.  A declaration that
  9800. prefigures a subsequent definition in this way is called a
  9801. @dfn{forward declaration}.  The function declaration can be at top
  9802. @c ??? file scope
  9803. level or within a block, and it applies until the end of the containing
  9804. scope.
  9805. @xref{Function Declarations}, for more information about these
  9806. declarations.
  9807. @node Static Functions
  9808. @subsection Static Functions
  9809. @cindex static functions
  9810. @cindex functions, static
  9811. @findex static
  9812. The keyword @code{static} in a function definition limits the
  9813. visibility of the name to the current compilation module.  (That's the
  9814. same thing @code{static} does in variable declarations;
  9815. @pxref{File-Scope Variables}.)  For instance, if one compilation module
  9816. contains this code:
  9817. @example
  9818. static int
  9819. foo (void)
  9820. @{
  9821.  @r{@dots{}}
  9822. @}
  9823. @end example
  9824. @noindent
  9825. then the code of that compilation module can call @code{foo} anywhere
  9826. after the definition, but other compilation modules cannot refer to it
  9827. at all.
  9828. @cindex forward declaration
  9829. @cindex static function, declaration
  9830. To call @code{foo} before its definition, it needs a forward
  9831. declaration, which should use @code{static} since the function
  9832. definition does.  For this function, it looks like this:
  9833. @example
  9834. static int foo (void);
  9835. @end example
  9836. It is generally wise to use @code{static} on the definitions of
  9837. functions that won't be called from outside the same compilation
  9838. module.  This makes sure that calls are not added in other modules.
  9839. If programmers decide to change the function's calling convention, or
  9840. understand all the consequences of its use, they will only have to
  9841. check for calls in the same compilation module.
  9842. @node Arrays as Parameters
  9843. @subsection Arrays as Parameters
  9844. @cindex array as parameters
  9845. @cindex functions with array parameters
  9846. Arrays in C are not first-class objects: it is impossible to copy
  9847. them.  So they cannot be passed as arguments like other values.
  9848. @xref{Limitations of C Arrays}.  Rather, array parameters work in
  9849. a special way.
  9850. @menu
  9851. * Array Parm Pointer::
  9852. * Passing Array Args::
  9853. * Array Parm Qualifiers::
  9854. @end menu
  9855. @node Array Parm Pointer
  9856. @subsubsection Array parameters are pointers
  9857. Declaring a function parameter variable as an array really gives it a
  9858. pointer type.  C does this because an expression with array type, if
  9859. used as an argument in a function call, is converted automatically to
  9860. a pointer (to the zeroth element of the array).  If you declare the
  9861. corresponding parameter as an ``array'', it will work correctly with
  9862. the pointer value that really gets passed.
  9863. This relates to the fact that C does not check array bounds in access
  9864. to elements of the array (@pxref{Accessing Array Elements}).
  9865. For example, in this function,
  9866. @example
  9867. void
  9868. clobber4 (int array[20])
  9869. @{
  9870.  array[4] = 0;
  9871. @}
  9872. @end example
  9873.  
  9874. @noindent
  9875. the parameter @code{array}'s real type is @code{int *}; the specified
  9876. length, 20, has no effect on the program.  You can leave out the length
  9877. and write this:
  9878.  
  9879. @example
  9880. void
  9881. clobber4 (int array[])
  9882. @{
  9883.  array[4] = 0;
  9884. @}
  9885. @end example
  9886.  
  9887. @noindent
  9888. or write the parameter declaration explicitly as a pointer:
  9889.  
  9890. @example
  9891. void
  9892. clobber4 (int *array)
  9893. @{
  9894.  array[4] = 0;
  9895. @}
  9896. @end example
  9897.  
  9898. They are all equivalent.
  9899.  
  9900. @node Passing Array Args
  9901. @subsubsection Passing array arguments
  9902.  
  9903.  The function call passes this pointer by
  9904. value, like all argument values in C@.  However, the result is
  9905. paradoxical in that the array itself is passed by reference: its
  9906. contents are treated as shared memory---shared between the caller and
  9907. the called function, that is.  When @code{clobber4} assigns to element
  9908. 4 of @code{array}, the effect is to alter element 4 of the array
  9909. specified in the call.
  9910.  
  9911. @example
  9912. #include <stddef.h>  /* @r{Defines @code{NULL}.} */
  9913. #include <stdlib.h>  /* @r{Declares @code{malloc},} */
  9914.                     /* @r{Defines @code{EXIT_SUCCESS}.} */
  9915.  
  9916. int
  9917. main (void)
  9918. @{
  9919.  int data[] = @{1, 2, 3, 4, 5, 6@};
  9920.  int i;
  9921.  
  9922.  /* @r{Show the initial value of element 4.} */
  9923.   for (i = 0; i < 6; i++)
  9924.     printf ("data[%d] = %d\n", i, data[i]);
  9925.  
  9926.   printf ("\n");
  9927.  
  9928.   clobber4 (data);
  9929.  
  9930.   /* @r{Show that element 4 has been changed.} */
  9931.   for (i = 0; i < 6; i++)
  9932.     printf ("data[%d] = %d\n", i, data[i]);
  9933.  
  9934.   printf ("\n");
  9935.  
  9936.   return EXIT_SUCCESS;
  9937. @}
  9938. @end example
  9939.  
  9940. @noindent
  9941. shows that @code{data[4]} has become zero after the call to
  9942. @code{clobber4}.
  9943.  
  9944. The array @code{data} has 6 elements, but passing it to a function
  9945. whose argument type is written as @code{int [20]} is not an error,
  9946. because that really stands for @code{int *}.  The pointer that is the
  9947. real argument carries no indication of the length of the array it
  9948. points into.  It is not required to point to the beginning of the
  9949. array, either.  For instance,
  9950.  
  9951. @example
  9952. clobber4 (data+1);
  9953. @end example
  9954.  
  9955. @noindent
  9956. passes an ``array'' that starts at element 1 of @code{data}, and the
  9957. effect is to zero @code{data[5]} instead of @code{data[4]}.
  9958.  
  9959. If all calls to the function will provide an array of a particular
  9960. size, you can specify the size of the array to be @code{static}:
  9961.  
  9962. @example
  9963. void
  9964. clobber4 (int array[static 20])
  9965. @r{@dots{}}
  9966. @end example
  9967.  
  9968. @noindent
  9969. This is a promise to the compiler that the function will always be
  9970. called with an array of 20 elements, so that the compiler can optimize
  9971. code accordingly.  If the code breaks this promise and calls the
  9972. function with, for example, a shorter array, unpredictable things may
  9973. happen.
  9974.  
  9975. @node Array Parm Qualifiers
  9976. @subsubsection Type qualifiers on array parameters
  9977.  
  9978. You can use the type qualifiers @code{const}, @code{restrict}, and
  9979. @code{volatile} with array parameters; for example:
  9980.  
  9981. @example
  9982. void
  9983. clobber4 (volatile int array[20])
  9984. @r{@dots{}}
  9985. @end example
  9986.  
  9987. @noindent
  9988. denotes that @code{array} is equivalent to a pointer to a volatile
  9989. @code{int}.  Alternatively:
  9990.  
  9991. @example
  9992. void
  9993. clobber4 (int array[const 20])
  9994. @r{@dots{}}
  9995. @end example
  9996.  
  9997. @noindent
  9998. makes the array parameter equivalent to a constant pointer to an
  9999. @code{int}.  If we want the @code{clobber4} function to succeed, it
  10000. would not make sense to write
  10001.  
  10002. @example
  10003. void
  10004. clobber4 (const int array[20])
  10005. @r{@dots{}}
  10006. @end example
  10007.  
  10008. @noindent
  10009. as this would tell the compiler that the parameter should point to an
  10010. array of constant @code{int} values, and then we would not be able to
  10011. store zeros in them.
  10012.  
  10013. In a function with multiple array parameters, you can use @code{restrict}
  10014. to tell the compiler that each array parameter passed in will be distinct:
  10015.  
  10016. @example
  10017. void
  10018. foo (int array1[restrict 10], int array2[restrict 10])
  10019. @r{@dots{}}
  10020. @end example
  10021.  
  10022. @noindent
  10023. Using @code{restrict} promises the compiler that callers will
  10024. not pass in the same array for more than one @code{restrict} array
  10025. parameter.  Knowing this enables the compiler to perform better code
  10026. optimization. This is the same effect as using @code{restrict}
  10027. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  10028. the code that an array of a specific size is expected.
  10029.  
  10030. @node Structs as Parameters
  10031. @subsection Functions That Accept Structure Arguments
  10032.  
  10033. Structures in GNU C are first-class objects, so using them as function
  10034. parameters and arguments works in the natural way.  This function
  10035. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  10036. and returns a structure of the same type but with the fields
  10037. exchanged.
  10038.  
  10039. @example
  10040. struct foo @{ int a, b; @};
  10041.  
  10042. struct foo x;
  10043.  
  10044. struct foo
  10045. swapfoo (struct foo inval)
  10046. @{
  10047.  struct foo outval;
  10048.  outval.a = inval.b;
  10049.  outval.b = inval.a;
  10050.  return outval;
  10051. @}
  10052. @end example
  10053.  
  10054. This simpler definition of @code{swapfoo} avoids using a local
  10055. variable to hold the result about to be return, by using a structure
  10056. constructor (@pxref{Structure Constructors}), like this:
  10057.  
  10058. @example
  10059. struct foo
  10060. swapfoo (struct foo inval)
  10061. @{
  10062.  return (struct foo) @{ inval.b, inval.a @};
  10063. @}
  10064. @end example
  10065.  
  10066. It is valid to define a structure type in a function's parameter list,
  10067. as in
  10068.  
  10069. @example
  10070. int
  10071. frob_bar (struct bar @{ int a, b; @} inval)
  10072. @{
  10073.  @var{body}
  10074. @}
  10075. @end example
  10076.  
  10077. @noindent
  10078. and @var{body} can access the fields of @var{inval} since the
  10079. structure type @code{struct bar} is defined for the whole function
  10080. body.  However, there is no way to create a @code{struct bar} argument
  10081. to pass to @code{frob_bar}, except with kludges.  As a result,
  10082. defining a structure type in a parameter list is useless in practice.
  10083.  
  10084. @node Function Declarations
  10085. @section Function Declarations
  10086. @cindex function declarations
  10087. @cindex declararing functions
  10088.  
  10089. To call a function, or use its name as a pointer, a @dfn{function
  10090. declaration} for the function name must be in effect at that point in
  10091. the code.  The function's definition serves as a declaration of that
  10092. function for the rest of the containing scope, but to use the function
  10093. in code before the definition, or from another compilation module, a
  10094. separate function declaration must precede the use.
  10095.  
  10096. A function declaration looks like the start of a function definition.
  10097. It begins with the return value type (@code{void} if none) and the
  10098. function name, followed by argument declarations in parentheses
  10099. (though these can sometimes be omitted).  But that's as far as the
  10100. similarity goes: instead of the function body, the declaration uses a
  10101. semicolon.
  10102.  
  10103. @cindex function prototype
  10104. @cindex prototype of a function
  10105. A declaration that specifies argument types is called a @dfn{function
  10106. prototype}.  You can include the argument names or omit them.  The
  10107. names, if included in the declaration, have no effect, but they may
  10108. serve as documentation.
  10109.  
  10110. This form of prototype specifies fixed argument types:
  10111.  
  10112. @example
  10113. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  10114. @end example
  10115.  
  10116. @noindent
  10117. This form says the function takes no arguments:
  10118.  
  10119. @example
  10120. @var{rettype} @var{function} (void);
  10121. @end example
  10122.  
  10123. @noindent
  10124. This form declares types for some arguments, and allows additional
  10125. arguments whose types are not specified:
  10126.  
  10127. @example
  10128. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  10129. @end example
  10130.  
  10131. For a parameter that's an array of variable length, you can write
  10132. its declaration with @samp{*} where the ``length'' of the array would
  10133. normally go; for example, these are all equivalent.
  10134.  
  10135. @example
  10136. double maximum (int n, int m, double a[n][m]);
  10137. double maximum (int n, int m, double a[*][*]);
  10138. double maximum (int n, int m, double a[ ][*]);
  10139. double maximum (int n, int m, double a[ ][m]);
  10140. @end example
  10141.  
  10142. @noindent
  10143. The old-fashioned form of declaration, which is not a prototype, says
  10144. nothing about the types of arguments or how many they should be:
  10145.  
  10146. @example
  10147. @var{rettype} @var{function} ();
  10148. @end example
  10149.  
  10150. @strong{Warning:} Arguments passed to a function declared without a
  10151. prototype are converted with the default argument promotions
  10152. (@pxref{Argument Promotions}.  Likewise for additional arguments whose
  10153. types are unspecified.
  10154.  
  10155. Function declarations are usually written at the top level in a source file,
  10156. but you can also put them inside code blocks.  Then the function name
  10157. is visible for the rest of the containing scope.  For example:
  10158.  
  10159. @example
  10160. void
  10161. foo (char *file_name)
  10162. @{
  10163.  void save_file (char *);
  10164.  save_file (file_name);
  10165. @}
  10166. @end example
  10167.  
  10168. If another part of the code tries to call the function
  10169. @code{save_file}, this declaration won't be in effect there.  So the
  10170. function will get an implicit declaration of the form @code{extern int
  10171. save_file ();}.   That conflicts with the explicit declaration
  10172. here, and the discrepancy generates a warning.
  10173.  
  10174. The syntax of C traditionally allows omitting the data type in a
  10175. function declaration if it specifies a storage class or a qualifier.
  10176. Then the type defaults to @code{int}.  For example:
  10177.  
  10178. @example
  10179. static foo (double x);
  10180. @end example
  10181.  
  10182. @noindent
  10183. defaults the return type to @code{int}.
  10184. This is bad practice; if you see it, fix it.
  10185.  
  10186. Calling a function that is undeclared has the effect of an creating
  10187. @dfn{implicit} declaration in the innermost containing scope,
  10188. equivalent to this:
  10189.  
  10190. @example
  10191. extern int @dfn{function} ();
  10192. @end example
  10193.  
  10194. @noindent
  10195. This declaration says that the function returns @code{int} but leaves
  10196. its argument types unspecified.  If that does not accurately fit the
  10197. function, then the program @strong{needs} an explicit declaration of
  10198. the function with argument types in order to call it correctly.
  10199.  
  10200. Implicit declarations are deprecated, and a function call that creates one
  10201. causes a warning.
  10202.  
  10203. @node Function Calls
  10204. @section Function Calls
  10205. @cindex function calls
  10206. @cindex calling functions
  10207.  
  10208. Starting a program automatically calls the function named @code{main}
  10209. (@pxref{The main Function}).  Aside from that, a function does nothing
  10210. except when it is @dfn{called}.  That occurs during the execution of a
  10211. function-call expression specifying that function.
  10212.  
  10213. A function-call expression looks like this:
  10214.  
  10215. @example
  10216. @var{function} (@var{arguments}@r{@dots{}})
  10217. @end example
  10218.  
  10219. Most of the time, @var{function} is a function name.  However, it can
  10220. also be an expression with a function pointer value; that way, the
  10221. program can determine at run time which function to call.
  10222.  
  10223. The @var{arguments} are a series of expressions separated by commas.
  10224. Each expression specifies one argument to pass to the function.
  10225.  
  10226. The list of arguments in a function call looks just like use of the
  10227. comma operator (@pxref{Comma Operator}), but the fact that it fills
  10228. the parentheses of a function call gives it a different meaning.
  10229.  
  10230. Here's an example of a function call, taken from an example near the
  10231. beginning (@pxref{Complete Program}).
  10232.  
  10233. @example
  10234. printf ("Fibonacci series item %d is %d\n",
  10235.         19, fib (19));
  10236. @end example
  10237.  
  10238. The three arguments given to @code{printf} are a constant string, the
  10239. integer 19, and the integer returned by @code{fib (19)}.
  10240.  
  10241. @node Function Call Semantics
  10242. @section Function Call Semantics
  10243. @cindex function call semantics
  10244. @cindex semantics of function calls
  10245. @cindex call-by-value
  10246.  
  10247. The meaning of a function call is to compute the specified argument
  10248. expressions, convert their values according to the function's
  10249. declaration, then run the function giving it copies of the converted
  10250. values.  (This method of argument passing is known as
  10251. @dfn{call-by-value}.)  When the function finishes, the value it
  10252. returns becomes the value of the function-call expression.
  10253.  
  10254. Call-by-value implies that an assignment to the function argument
  10255. variable has no direct effect on the caller.  For instance,
  10256.  
  10257. @example
  10258. #include <stdlib.h>  /* @r{Defines @code{EXIT_SUCCESS}.} */
  10259. #include <stdio.h>   /* @r{Declares @code{printf}.} */
  10260.  
  10261. void
  10262. subroutine (int x)
  10263. @{
  10264.  x = 5;
  10265. @}
  10266.  
  10267. void
  10268. main (void)
  10269. @{
  10270.   int y = 20;
  10271.   subroutine (y);
  10272.   printf ("y is %d\n", y);
  10273.   return EXIT_SUCCESS;
  10274. @}
  10275. @end example
  10276.  
  10277. @noindent
  10278. prints @samp{y is 20}.  Calling @code{subroutine} initializes @code{x}
  10279. from the value of @code{y}, but this does not establish any other
  10280. relationship between the two variables.  Thus, the assignment to
  10281. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  10282.  
  10283. If an argument's type is specified by the function's declaration, the
  10284. function call converts the argument expression to that type if
  10285. possible.  If the conversion is impossible, that is an error.
  10286.  
  10287. If the function's declaration doesn't specify the type of that
  10288. argument, then the @emph{default argument promotions} apply.
  10289. @xref{Argument Promotions}.
  10290.  
  10291. @node Function Pointers
  10292. @section Function Pointers
  10293. @cindex function pointers
  10294. @cindex pointers to functions
  10295.  
  10296. A function name refers to a fixed function.  Sometimes it is useful to
  10297. call a function to be determined at run time; to do this, you can use
  10298. a @dfn{function pointer value} that points to the chosen function
  10299. (@pxref{Pointers}).
  10300.  
  10301. Pointer-to-function types can be used to declare variables and other
  10302. data, including array elements, structure fields, and union
  10303. alternatives.  They can also be used for function arguments and return
  10304. values.  These types have the peculiarity that they are never
  10305. converted automatically to @code{void *} or vice versa.  However, you
  10306. can do that conversion with a cast.
  10307.  
  10308. @menu
  10309. * Declaring Function Pointers:: How to declare a pointer to a function.
  10310. * Assigning Function Pointers:: How to assign values to function pointers.
  10311. * Calling Function Pointers::   How to call functions through pointers.
  10312. @end menu
  10313.  
  10314. @node Declaring Function Pointers
  10315. @subsection Declaring Function Pointers
  10316. @cindex declaring function pointers
  10317. @cindex function pointers, declaring
  10318.  
  10319. The declaration of a function pointer variable (or structure field)
  10320. looks almost like a function declaration, except it has an additional
  10321. @samp{*} just before the variable name.  Proper nesting requires a
  10322. pair of parentheses around the two of them.  For instance, @code{int
  10323. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  10324. an @code{int}-returning function.''
  10325.  
  10326. Contrast these three declarations:
  10327.  
  10328. @example
  10329. /* @r{Declare a function returning @code{char *}.}  */
  10330. char *a (char *);
  10331. /* @r{Declare a pointer to a function returning @code{char}.}  */
  10332. char (*a) (char *);
  10333. /* @r{Declare a pointer to a function returning @code{char *}.}  */
  10334. char *(*a) (char *);
  10335. @end example
  10336.  
  10337. The possible argument types of the function pointed to are the same
  10338. as in a function declaration.  You can write a prototype
  10339. that specifies all the argument types:
  10340.  
  10341. @example
  10342. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  10343. @end example
  10344.  
  10345. @noindent
  10346. or one that specifies some and leaves the rest unspecified:
  10347.  
  10348. @example
  10349. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  10350. @end example
  10351.  
  10352. @noindent
  10353. or one that says there are no arguments:
  10354.  
  10355. @example
  10356. @var{rettype} (*@var{function}) (void);
  10357. @end example
  10358.  
  10359. You can also write a non-prototype declaration that says
  10360. nothing about the argument types:
  10361.  
  10362. @example
  10363. @var{rettype} (*@var{function}) ();
  10364. @end example
  10365.  
  10366. For example, here's a declaration for a variable that should
  10367. point to some arithmetic function that operates on two @code{double}s:
  10368.  
  10369. @example
  10370. double (*binary_op) (double, double);
  10371. @end example
  10372.  
  10373. Structure fields, union alternatives, and array elements can be
  10374. function pointers; so can parameter variables.  The function pointer
  10375. declaration construct can also be combined with other operators
  10376. allowed in declarations.  For instance,
  10377.  
  10378. @example
  10379. int **(*foo)();
  10380. @end example
  10381.  
  10382. @noindent
  10383. declares @code{foo} as a pointer to a function that returns
  10384. type @code{int **}, and
  10385.  
  10386. @example
  10387. int **(*foo[30])();
  10388. @end example
  10389.  
  10390. @noindent
  10391. declares @code{foo} as an array of 30 pointers to functions that
  10392. return type @code{int **}.
  10393.  
  10394. @example
  10395. int **(**foo)();
  10396. @end example
  10397.  
  10398. @noindent
  10399. declares @code{foo} as a pointer to a pointer to a function that
  10400. returns type @code{int **}.
  10401.  
  10402. @node Assigning Function Pointers
  10403. @subsection Assigning Function Pointers
  10404. @cindex assigning function pointers
  10405. @cindex function pointers, assigning
  10406.  
  10407. Assuming we have declared the variable @code{binary_op} as in the
  10408. previous section, giving it a value requires a suitable function to
  10409. use.  So let's define a function suitable for the variable to point
  10410. to.  Here's one:
  10411.  
  10412. @example
  10413. double
  10414. double_add (double a, double b)
  10415. @{
  10416.  return a+b;
  10417. @}
  10418. @end example
  10419.  
  10420. Now we can give it a value:
  10421.  
  10422. @example
  10423. binary_op = double_add;
  10424. @end example
  10425.  
  10426. The target type of the function pointer must be upward compatible with
  10427. the type of the function (@pxref{Compatible Types}).
  10428.  
  10429. There is no need for @samp{&} in front of @code{double_add}.
  10430. Using a function name such as @code{double_add} as an expression
  10431. automatically converts it to the function's address, with the
  10432. appropriate function pointer type.  However, it is ok to use
  10433. @samp{&} if you feel that is clearer:
  10434.  
  10435. @example
  10436. binary_op = &double_add;
  10437. @end example
  10438.  
  10439. @node Calling Function Pointers
  10440. @subsection Calling Function Pointers
  10441. @cindex calling function pointers
  10442. @cindex function pointers, calling
  10443.  
  10444. To call the function specified by a function pointer, just write the
  10445. function pointer value in a function call.  For instance, here's a
  10446. call to the function @code{binary_op} points to:
  10447.  
  10448. @example
  10449. binary_op (x, 5)
  10450. @end example
  10451.  
  10452. Since the data type of @code{binary_op} explicitly specifies type
  10453. @code{double} for the arguments, the call converts @code{x} and 5 to
  10454. @code{double}.
  10455.  
  10456. The call conceptually dereferences the pointer @code{binary_op} to
  10457. ``get'' the function it points to, and calls that function.  If you
  10458. wish, you can explicitly represent the derefence by writing the
  10459. @code{*} operator:
  10460.  
  10461. @example
  10462. (*binary_op) (x, 5)
  10463. @end example
  10464.  
  10465. The @samp{*} reminds people reading the code that @code{binary_op} is
  10466. a function pointer rather than the name of a specific function.
  10467.  
  10468. @node The main Function
  10469. @section The @code{main} Function
  10470. @cindex @code{main} function
  10471. @findex main
  10472.  
  10473. Every complete executable program requires at least one function,
  10474. called @code{main}, which is where execution begins.  You do not have
  10475. to explicitly declare @code{main}, though GNU C permits you to do so.
  10476. Conventionally, @code{main} should be defined to follow one of these
  10477. calling conventions:
  10478.  
  10479. @example
  10480. int main (void) @{@r{@dots{}}@}
  10481. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  10482. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  10483. @end example
  10484. @noindent
  10485. Using @code{void} as the parameter list means that @code{main} does
  10486. not use the arguments.  You can write @code{char **argv} instead of
  10487. @code{char *argv[]}, and likewise for @code{envp}, as the two
  10488. constructs are equivalent.
  10489. @ignore   @c Not so at present
  10490. Defining @code{main} in any other way generates a warning.  Your
  10491. program will still compile, but you may get unexpected results when
  10492. executing it.
  10493. @end ignore
  10494. You can call @code{main} from C code, as you can call any other
  10495. function, though that is an unusual thing to do.  When you do that,
  10496. you must write the call to pass arguments that match the parameters in
  10497. the definition of @code{main}.
  10498. The @code{main} function is not actually the first code that runs when
  10499. a program starts.  In fact, the first code that runs is system code
  10500. from the file @file{crt0.o}.  In Unix, this was hand-written assembler
  10501. code, but in GNU we replaced it with C code.  Its job is to find
  10502. the arguments for @code{main} and call that.
  10503. @menu
  10504. * Values from main::         Returning values from the main function.
  10505. * Command-line Parameters::  Accessing command-line parameters
  10506.                               provided to the program.
  10507. * Environment Variables::    Accessing system environment variables.
  10508. @end menu
  10509. @node Values from main
  10510. @subsection Returning Values from @code{main}
  10511. @cindex returning values from @code{main}
  10512. @cindex success
  10513. @cindex failure
  10514. @cindex exit status
  10515. When @code{main} returns, the process terminates.  Whatever value
  10516. @code{main} returns becomes the exit status which is reported to the
  10517. parent process.  While nominally the return value is of type
  10518. @code{int}, in fact the exit status gets truncated to eight bits; if
  10519. @code{main} returns the value 256, the exit status is 0.
  10520. Normally, programs return only one of two values: 0 for success,
  10521. and 1 for failure. For maximum portability, use the macro
  10522. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  10523. @code{stdlib.h}.  Here's an example:
  10524. @cindex @code{EXIT_FAILURE}
  10525. @cindex @code{EXIT_SUCCESS}
  10526. @example
  10527. #include <stdlib.h>  /* @r{Defines @code{EXIT_SUCCESS}} */
  10528.                     /* @r{and @code{EXIT_FAILURE}.} */
  10529. int
  10530. main (void)
  10531. @{
  10532.  @r{@dots{}}
  10533.  if (foo)
  10534.    return EXIT_SUCCESS;
  10535.  else
  10536.    return EXIT_FAILURE;
  10537. @}
  10538. @end example
  10539. Some types of programs maintain special conventions for various return
  10540. values; for example, comparison programs including @code{cmp} and
  10541. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  10542. the comparison couldn't be performed.
  10543. @node Command-line Parameters
  10544. @subsection Accessing Command-line Parameters
  10545. @cindex command-line parameters
  10546. @cindex parameters, command-line
  10547. If the program was invoked with any command-line arguments, it can
  10548. access them through the arguments of @code{main}, @code{argc} and
  10549. @code{argv}.  (You can give these arguments any names, but the names
  10550. @code{argc} and @code{argv} are customary.)
  10551. The value of @code{argv} is an array containing all of the
  10552. command-line arguments as strings, with the name of the command
  10553. invoked as the first string.  @code{argc} is an integer that says how
  10554. many strings @code{argv} contains.  Here is an example of accessing
  10555. the command-line parameters, retrieving the program's name and
  10556. checking for the standard @option{--version} and @option{--help} options:
  10557. @example
  10558. #include <string.h> /* @r{Declare @code{strcmp}.} */
  10559. int
  10560. main (int argc, char *argv[])
  10561. @{
  10562.  char *program_name = argv[0];
  10563.  
  10564.  for (int i = 1; i < argc; i++)
  10565.    @{
  10566.      if (!strcmp (argv[i], "--version"))
  10567.        @{
  10568.          /* @r{Print version information and exit.} */
  10569.          @r{@dots{}}
  10570.        @}
  10571.      else if (!strcmp (argv[i], "--help"))
  10572.        @{
  10573.          /* @r{Print help information and exit.} */
  10574.          @r{@dots{}}
  10575.        @}
  10576.    @}
  10577.  @r{@dots{}}
  10578. @}
  10579. @end example
  10580.  
  10581. @node Environment Variables
  10582. @subsection Accessing Environment Variables
  10583. @cindex environment variables
  10584.  
  10585. You can optionally include a third parameter to @code{main}, another
  10586. array of strings, to capture the environment variables available to
  10587. the program.  Unlike what happens with @code{argv}, there is no
  10588. additional parameter for the count of environment variables; rather,
  10589. the array of environment variables concludes with a null pointer.
  10590.  
  10591. @example
  10592. #include <stdio.h>   /* @r{Declares @code{printf}.} */
  10593.  
  10594. int
  10595. main (int argc, char *argv[], char *envp[])
  10596. @{
  10597.  /* @r{Print out all environment variables.} */
  10598.  int i = 0;
  10599.  while (envp[i])
  10600.     @{
  10601.       printf ("%s\n", envp[i]);
  10602.       i++;
  10603.     @}
  10604. @}
  10605. @end example
  10606.  
  10607. Another method of retrieving environment variables is to use the
  10608. library function @code{getenv}, which is defined in @code{stdlib.h}.
  10609. Using @code{getenv} does not require defining @code{main} to accept the
  10610. @code{envp} pointer.  For example, here is a program that fetches and prints
  10611. the user's home directory (if defined):
  10612.  
  10613. @example
  10614. #include <stdlib.h>  /* @r{Declares @code{getenv}.} */
  10615. #include <stdio.h>   /* @r{Declares @code{printf}.} */
  10616.  
  10617. int
  10618. main (void)
  10619. @{
  10620.   char *home_directory = getenv ("HOME");
  10621.   if (home_directory)
  10622.     printf ("My home directory is: %s\n", home_directory);
  10623.   else
  10624.     printf ("My home directory is not defined!\n");
  10625. @}
  10626. @end example
  10627.  
  10628. @node Advanced Definitions
  10629. @section Advanced Function Features
  10630.  
  10631. This section describes some advanced or obscure features for GNU C
  10632. function definitions.  If you are just learning C, you can skip the
  10633. rest of this chapter.
  10634.  
  10635. @menu
  10636. * Variable-Length Array Parameters:: Functions that accept arrays
  10637.                                        of variable length.
  10638. * Variable Number of Arguments::     Variadic functions.
  10639. * Nested Functions::                 Defining functions within functions.
  10640. * Inline Function Definitions::      A function call optimization technique.
  10641. @end menu
  10642.  
  10643. @node Variable-Length Array Parameters
  10644. @subsection Variable-Length Array Parameters
  10645. @cindex variable-length array parameters
  10646. @cindex array parameters, variable-length
  10647. @cindex functions that accept variable-length arrays
  10648.  
  10649. An array parameter can have variable length: simply declare the array
  10650. type with a size that isn't constant.  In a nested function, the
  10651. length can refer to a variable defined in a containing scope.  In any
  10652. function, it can refer to a previous parameter, like this:
  10653.  
  10654. @example
  10655. struct entry
  10656. tester (int len, char data[len][len])
  10657. @{
  10658.  @r{@dots{}}
  10659. @}
  10660. @end example
  10661.  
  10662. Alternatively, in function declarations (but not in function
  10663. definitions), you can use @code{[*]} to denote that the array
  10664. parameter is of a variable length, such that these two declarations
  10665. mean the same thing:
  10666.  
  10667. @example
  10668. struct entry
  10669. tester (int len, char data[len][len]);
  10670. @end example
  10671.  
  10672. @example
  10673. struct entry
  10674. tester (int len, char data[*][*]);
  10675. @end example
  10676.  
  10677. @noindent
  10678. The two forms of input are equivalent in GNU C, but emphasizing that
  10679. the array parameter is variable-length may be helpful to those
  10680. studying the code.
  10681.  
  10682. You can also omit the length parameter, and instead use some other
  10683. in-scope variable for the length in the function definition:
  10684.  
  10685. @example
  10686. struct entry
  10687. tester (char data[*][*]);
  10688. @r{@dots{}}
  10689. int dataLength = 20;
  10690. @r{@dots{}}
  10691. struct entry
  10692. tester (char data[dataLength][dataLength])
  10693. @{
  10694.  @r{@dots{}}
  10695. @}
  10696. @end example
  10697.  
  10698. @c ??? check text above
  10699.  
  10700. @cindex parameter forward declaration
  10701. In GNU C, to pass the array first and the length afterward, you can
  10702. use a @dfn{parameter forward declaration}, like this:
  10703.  
  10704. @example
  10705. struct entry
  10706. tester (int len; char data[len][len], int len)
  10707. @{
  10708.  @r{@dots{}}
  10709. @}
  10710. @end example
  10711.  
  10712. The @samp{int len} before the semicolon is the parameter forward
  10713. declaration; it serves the purpose of making the name @code{len} known
  10714. when the declaration of @code{data} is parsed.
  10715.  
  10716. You can write any number of such parameter forward declarations in the
  10717. parameter list.  They can be separated by commas or semicolons, but
  10718. the last one must end with a semicolon, which is followed by the
  10719. ``real'' parameter declarations.  Each forward declaration must match
  10720. a subsequent ``real'' declaration in parameter name and data type.
  10721.  
  10722. Standard C does not support parameter forward declarations.
  10723.  
  10724. @node Variable Number of Arguments
  10725. @subsection Variable-Length Parameter Lists
  10726. @cindex variable-length parameter lists
  10727. @cindex parameters lists, variable length
  10728. @cindex function parameter lists, variable length
  10729.  
  10730. @cindex variadic function
  10731. A function that takes a variable number of arguments is called a
  10732. @dfn{variadic function}.  In C, a variadic function must specify at
  10733. least one fixed argument with an explicitly declared data type.
  10734. Additional arguments can follow, and can vary in both quantity and
  10735. data type.
  10736.  
  10737. In the function header, declare the fixed parameters in the normal
  10738. way, then write a comma and an ellipsis: @samp{, ...}.  Here is an
  10739. example of a variadic function header:
  10740.  
  10741. @example
  10742. int add_multiple_values (int number, ...)
  10743. @end example
  10744.  
  10745. @cindex @code{va_list}
  10746. @cindex @code{va_start}
  10747. @cindex @code{va_end}
  10748. The function body can refer to fixed arguments by their parameter
  10749. names, but the additional arguments have no names.  Accessing them in
  10750. the function body uses certain standard macros.  They are defined in
  10751. the library header file @file{stdarg.h}, so the code must
  10752. @code{#include} that file.
  10753.  
  10754. In the body, write
  10755.  
  10756. @example
  10757. va_list ap;
  10758. va_start (ap, @var{last_fixed_parameter});
  10759. @end example
  10760.  
  10761. @noindent
  10762. This declares the variable @code{ap} (you can use any name for it)
  10763. and then sets it up to point before the first additional argument.
  10764.  
  10765. Then, to fetch the next consecutive additional argument, write this:
  10766.  
  10767. @example
  10768. va_arg (ap, @var{type})
  10769. @end example
  10770.  
  10771. After fetching all the additional arguments (or as many as need to be
  10772. used), write this:
  10773.  
  10774. @example
  10775. va_end (ap);
  10776. @end example
  10777.  
  10778. Here's an example of a variadic function definition that adds any
  10779. number of @code{int} arguments.  The first (fixed) argument says how
  10780. many more arguments follow.
  10781.  
  10782. @example
  10783. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  10784. @r{@dots{}}
  10785.  
  10786. int
  10787. add_multiple_values (int argcount, ...)
  10788. @{
  10789.  int counter, total = 0;
  10790.  
  10791.  /* @r{Declare a variable of type @code{va_list}.} */
  10792.  va_list argptr;
  10793.  
  10794.  /* @r{Initialize that variable..} */
  10795.  va_start (argptr, argcount);
  10796.  
  10797.  for (counter = 0; counter < argcount; counter++)
  10798.    @{
  10799.      /* @r{Get the next additional argument.} */
  10800.      total += va_arg (argptr, int);
  10801.    @}
  10802.  
  10803.  /* @r{End use of the @code{argptr} variable.} */
  10804.  va_end (argptr);
  10805.  
  10806.  return total;
  10807. @}
  10808. @end example
  10809.  
  10810. With GNU C, @code{va_end} is superfluous, but some other compilers
  10811. might make @code{va_start} allocate memory so that calling
  10812. @code{va_end} is necessary to avoid a memory leak.  Before doing
  10813. @code{va_start} again with the same variable, do @code{va_end}
  10814. first.
  10815.  
  10816. @cindex @code{va_copy}
  10817. Because of this possible memory allocation, it is risky (in principle)
  10818. to copy one @code{va_list} variable to another with assignment.
  10819. Instead, use @code{va_copy}, which copies the substance but allocates
  10820. separate memory in the variable you copy to.  The call looks like
  10821. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  10822. @var{from} should be variables of type @code{va_list}.  In principle,
  10823. do @code{va_end} on each of these variables before its scope ends.
  10824.  
  10825. Since the additional arguments' types are not specified in the
  10826. function's definition, the default argument promotions
  10827. (@pxref{Argument Promotions}) apply to them in function calls.  The
  10828. function definition must take account of this; thus, if an argument
  10829. was passed as @code{short}, the function should get it as @code{int}.
  10830. If an argument was passed as @code{float}, the function should get it
  10831. as @code{double}.
  10832.  
  10833. C has no mechanism to tell the variadic function how many arguments
  10834. were passed to it, so its calling convention must give it a way to
  10835. determine this.  That's why @code{add_multiple_values} takes a fixed
  10836. argument that says how many more arguments follow.  Thus, you can
  10837. call the function like this:
  10838.  
  10839. @example
  10840. sum = add_multiple_values (3, 12, 34, 190);
  10841. /* @r{Value is 12+34+190.} */
  10842. @end example
  10843.  
  10844. In GNU C, there is no actual need to use the @code{va_end} function.
  10845. In fact, it does nothing.  It's used for compatibility with other
  10846. compilers, when that matters.
  10847.  
  10848. It is a mistake to access variables declared as @code{va_list} except
  10849. in the specific ways described here.  Just what that type consists of
  10850. is an implementation detail, which could vary from one platform to
  10851. another.
  10852.  
  10853. @node Nested Functions
  10854. @subsection Nested Functions
  10855. @cindex nested functions
  10856. @cindex functions, nested
  10857. @cindex downward funargs
  10858. @cindex thunks
  10859.  
  10860. A @dfn{nested function} is a function defined inside another function.
  10861. The nested function's name is local to the block where it is defined.
  10862. For example, here we define a nested function named @code{square}, and
  10863. call it twice:
  10864.  
  10865. @example
  10866. @group
  10867. foo (double a, double b)
  10868. @{
  10869.  double square (double z) @{ return z * z; @}
  10870.  
  10871.  return square (a) + square (b);
  10872. @}
  10873. @end group
  10874. @end example
  10875.  
  10876. The nested function can access all the variables of the containing
  10877. function that are visible at the point of its definition.  This is
  10878. called @dfn{lexical scoping}.  For example, here we show a nested
  10879. function that uses an inherited variable named @code{offset}:
  10880.  
  10881. @example
  10882. @group
  10883. bar (int *array, int offset, int size)
  10884. @{
  10885.  int access (int *array, int index)
  10886.    @{ return array[index + offset]; @}
  10887.  int i;
  10888.  @r{@dots{}}
  10889.  for (i = 0; i < size; i++)
  10890.    @r{@dots{}} access (array, i) @r{@dots{}}
  10891. @}
  10892. @end group
  10893. @end example
  10894.  
  10895. Nested function definitions can appear wherever automatic variable
  10896. declarations are allowed; that is, in any block, interspersed with the
  10897. other declarations and statements in the block.
  10898.  
  10899. The nested function's name is visible only within the parent block;
  10900. the name's scope starts from its definition and continues to the end
  10901. of the containing block.  If the nested function's name
  10902. is the same as the parent function's name, there wil be
  10903. no way to refer to the parent function inside the scope of the
  10904. name of the nested function.
  10905.  
  10906. Using @code{extern} or @code{static} on a nested function definition
  10907. is an error.
  10908.  
  10909. It is possible to call the nested function from outside the scope of its
  10910. name by storing its address or passing the address to another function.
  10911. You can do this safely, but you must be careful:
  10912.  
  10913. @example
  10914. @group
  10915. hack (int *array, int size, int addition)
  10916. @{
  10917.  void store (int index, int value)
  10918.    @{ array[index] = value + addition; @}
  10919.  
  10920.  intermediate (store, size);
  10921. @}
  10922. @end group
  10923. @end example
  10924.  
  10925. Here, the function @code{intermediate} receives the address of
  10926. @code{store} as an argument.  If @code{intermediate} calls @code{store},
  10927. the arguments given to @code{store} are used to store into @code{array}.
  10928. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  10929.  
  10930. It is safe for @code{intermediate} to call @code{store} because
  10931. @code{hack}'s stack frame, with its arguments and local variables,
  10932. continues to exist during the call to @code{intermediate}.
  10933.  
  10934. Calling the nested function through its address after the containing
  10935. function has exited is asking for trouble.  If it is called after a
  10936. containing scope level has exited, and if it refers to some of the
  10937. variables that are no longer in scope, it will refer to memory
  10938. containing junk or other data.  It's not wise to take the risk.
  10939.  
  10940. The GNU C Compiler implements taking the address of a nested function
  10941. using a technique called @dfn{trampolines}.  This technique was
  10942. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  10943. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  10944.  
  10945. A nested function can jump to a label inherited from a containing
  10946. function, provided the label was explicitly declared in the containing
  10947. function (@pxref{Local Labels}).  Such a jump returns instantly to the
  10948. containing function, exiting the nested function that did the
  10949. @code{goto} and any intermediate function invocations as well.  Here
  10950. is an example:
  10951.  
  10952. @example
  10953. @group
  10954. bar (int *array, int offset, int size)
  10955. @{
  10956.  /* @r{Explicitly declare the label @code{failure}.} */
  10957.  __label__ failure;
  10958.  int access (int *array, int index)
  10959.    @{
  10960.      if (index > size)
  10961.        /* @r{Exit this function,}
  10962.           @r{and return to @code{bar}.} */
  10963.        goto failure;
  10964.      return array[index + offset];
  10965.    @}
  10966. @end group
  10967.  
  10968. @group
  10969.  int i;
  10970.  @r{@dots{}}
  10971.  for (i = 0; i < size; i++)
  10972.    @r{@dots{}} access (array, i) @r{@dots{}}
  10973.  @r{@dots{}}
  10974.  return 0;
  10975.  
  10976. /* @r{Control comes here from @code{access}
  10977.    if it does the @code{goto}.}  */
  10978. failure:
  10979.  return -1;
  10980. @}
  10981. @end group
  10982. @end example
  10983.  
  10984. To declare the nested function before its definition, use
  10985. @code{auto} (which is otherwise meaningless for function declarations;
  10986. @pxref{auto and register}).  For example,
  10987.  
  10988. @example
  10989. bar (int *array, int offset, int size)
  10990. @{
  10991.  auto int access (int *, int);
  10992.  @r{@dots{}}
  10993.  @r{@dots{}} access (array, i) @r{@dots{}}
  10994.  @r{@dots{}}
  10995.  int access (int *array, int index)
  10996.    @{
  10997.      @r{@dots{}}
  10998.    @}
  10999.  @r{@dots{}}
  11000. @}
  11001. @end example
  11002.  
  11003. @node Inline Function Definitions
  11004. @subsection Inline Function Definitions
  11005. @cindex inline function definitions
  11006. @cindex function definitions, inline
  11007. @findex inline
  11008.  
  11009. To declare a function inline, use the @code{inline} keyword in its
  11010. definition.  Here's a simple function that takes a pointer-to-@code{int}
  11011. and increments the integer stored there---declared inline.
  11012.  
  11013. @example
  11014. struct list
  11015. @{
  11016.  struct list *first, *second;
  11017. @};
  11018.  
  11019. inline struct list *
  11020. list_first (struct list *p)
  11021. @{
  11022.  return p->first;  
  11023. @}
  11024.  
  11025. inline struct list *
  11026. list_second (struct list *p)
  11027. @{
  11028.  return p->second;  
  11029. @}
  11030. @end example
  11031.  
  11032. optimized compilation can substitute the inline function's body for
  11033. any call to it.  This is called @emph{inlining} the function.  It
  11034. makes the code that contains the call run faster, significantly so if
  11035. the inline function is small.
  11036.  
  11037. Here's a function that uses @code{pair_second}:
  11038.  
  11039. @example
  11040. int
  11041. pairlist_length (struct list *l)
  11042. @{
  11043.  int length = 0;
  11044.  while (l)
  11045.    @{
  11046.      length++;
  11047.      l = pair_second (l);
  11048.    @}
  11049.  return length;
  11050. @}
  11051. @end example
  11052.  
  11053. Substituting the code of @code{pair_second} into the definition of
  11054. @code{pairlist_length} results in this code, in effect:
  11055.  
  11056. @example
  11057. int
  11058. pairlist_length (struct list *l)
  11059. @{
  11060.  int length = 0;
  11061.  while (l)
  11062.    @{
  11063.      length++;
  11064.      l = l->second;
  11065.    @}
  11066.  return length;
  11067. @}
  11068. @end example
  11069.  
  11070. Since the definition of @code{pair_second} does not say @code{extern}
  11071. or @code{static}, that definition is used only for inlining.  It
  11072. doesn't generate code that can be called at run time.  If not all the
  11073. calls to the function are inlined, there must be a definition of the
  11074. same function name in another module for them to call.
  11075.  
  11076. @cindex inline functions, omission of
  11077. @c @opindex fkeep-inline-functions
  11078. Adding @code{static} to an inline function definition means the
  11079. function definition is limited to this compilation module.  Also, it
  11080. generates run-time code if necessary for the sake of any calls that
  11081. were not inlined.  If all calls are inlined then the function
  11082. definition does not generate run-time code, but you can force
  11083. generation of run-time code with the option
  11084. @option{-fkeep-inline-functions}.
  11085.  
  11086. @cindex extern inline function
  11087. Specifying @code{extern} along with @code{inline} means the function is
  11088. external and generates run-time code to be called from other
  11089. separately compiled modules, as well as inlined.  You can define the
  11090. function as @code{inline} without @code{extern} in other modules so as
  11091. to inline calls to the same function in those modules.
  11092.  
  11093. Why are some calls not inlined?  First of all, inlining is an
  11094. optimization, so non-optimized compilation does not inline.
  11095.  
  11096. Some calls cannot be inlined for technical reasons.  Also, certain
  11097. usages in a function definition can make it unsuitable for inline
  11098. substitution.  Among these usages are: variadic functions, use of
  11099. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  11100. use of nonlocal goto.  The option @option{-Winline} requests a warning
  11101. when a function marked @code{inline} is unsuitable to be inlined.  The
  11102. warning explains what obstacle makes it unsuitable.
  11103.  
  11104. Just because a call @emph{can} be inlined does not mean it
  11105. @emph{should} be inlined.  The GNU C compiler weighs costs and
  11106. benefits to decide whether inlining a particular call is advantageous.
  11107.  
  11108. You can force inlining of all calls to a given function that can be
  11109. inlined, even in a non-optimized compilation. by specifying the
  11110. @samp{always_inline} attribute for the function, like this:
  11111.  
  11112. @example
  11113. /* @r{Prototype.}  */
  11114. inline void foo (const char) __attribute__((always_inline));
  11115. @end example
  11116.  
  11117. @noindent
  11118. This is a GNU C extension.  @xref{Attributes}.
  11119.  
  11120. A function call may be inlined even if not declared @code{inline} in
  11121. special cases where the compiler can determine this is correct and
  11122. desirable.  For instance, when a static function is called only once,
  11123. it will very likely be inlined.  With @option{-flto}, link-time
  11124. optimization, any function might be inlined.  To absolutely prevent
  11125. inlining of a specific function, specify
  11126. @code{__attribute__((__noinline__))} in the function's definition.
  11127.  
  11128. @node Obsolete Definitions
  11129. @section Obsolete Function Features
  11130.  
  11131. These features of function definitions are still used in old
  11132. programs, but you shouldn't write code this way today.
  11133. If you are just learning C, you can skip this section.
  11134.  
  11135. @menu
  11136. * Old GNU Inlining::                 An older inlining technique.
  11137. * Old-Style Function Definitions::   Original K&R style functions.
  11138. @end menu
  11139.  
  11140. @node Old GNU Inlining
  11141. @subsection Older GNU C Inlining
  11142.  
  11143. The GNU C spec for inline functions, before GCC version 5, defined
  11144. @code{extern inline} on a function definition to mean to inline calls
  11145. to it but @emph{not} generate code for the function that could be
  11146. called at run time.  By contrast, @code{inline} without @code{extern}
  11147. specified to generate run-time code for the function.  In effect, ISO
  11148. incompatibly flipped the meanings of these two cases.  We changed GCC
  11149. in version 5 to adopt the ISO specification.
  11150.  
  11151. Many programs still use these cases with the previous GNU C meanings.
  11152. You can specify use of those meanings with the option
  11153. @option{-fgnu89-inline}.  You can also specify this for a single
  11154. function with @code{__attribute__ ((gnu_inline))}.  Here's an example:
  11155.  
  11156. @example
  11157. inline __attribute__ ((gnu_inline))
  11158. int
  11159. inc (int *a)
  11160. @{
  11161.  (*a)++;
  11162. @}
  11163. @end example
  11164.  
  11165. @node Old-Style Function Definitions
  11166. @subsection Old-Style Function Definitions
  11167. @cindex old-style function definitions
  11168. @cindex function definitions, old-style
  11169. @cindex K&R-style function definitions
  11170.  
  11171. The syntax of C traditionally allows omitting the data type in a
  11172. function declaration if it specifies a storage class or a qualifier.
  11173. Then the type defaults to @code{int}.  For example:
  11174.  
  11175. @example
  11176. static foo (double x);
  11177. @end example
  11178.  
  11179. @noindent
  11180. defaults the return type to @code{int}.  This is bad practice; if you
  11181. see it, fix it.
  11182.  
  11183. An @dfn{old-style} (or ``K&R'') function definition is the way
  11184. function definitions were written in the 1980s.  It looks like this:
  11185.  
  11186. @example
  11187. @var{rettype}
  11188. @var{function} (@var{parmnames})
  11189.  @var{parm_declarations}
  11190. @{
  11191.  @var{body}
  11192. @}
  11193. @end example
  11194.  
  11195. In @var{parmnames}, only the parameter names are listed, separated by
  11196. commas.  Then @var{parm_declarations} declares their data types; these
  11197. declarations look just like variable declarations.  If a parameter is
  11198. listed in @var{parmnames} but has no declaration, it is implicitly
  11199. declared @code{int}.
  11200.  
  11201. There is no reason to write a definition this way nowadays, but they
  11202. can still be seen in older GNU programs.
  11203.  
  11204. An old-style variadic function definition looks like this:
  11205.  
  11206. @example
  11207. #include <varargs.h>
  11208.  
  11209. int
  11210. add_multiple_values (va_alist)
  11211.    va_dcl
  11212. @{
  11213.  int argcount;
  11214.  int counter, total = 0;
  11215.  
  11216.  /* @r{Declare a variable of type @code{va_list}.} */
  11217.  va_list argptr;
  11218.  
  11219.  /* @r{Initialize that variable.} */
  11220.  va_start (argptr);
  11221.  
  11222.  /* @r{Get the first argument (fixed).} */
  11223.  argcount = va_arg (int);
  11224.  
  11225.  for (counter = 0; counter < argcount; counter++)
  11226.    @{
  11227.      /* @r{Get the next additional argument.} */
  11228.      total += va_arg (argptr, int);
  11229.    @}
  11230.  
  11231.  /* @r{End use of the @code{argptr} variable.} */
  11232.  va_end (argptr);
  11233.  
  11234.  return total;
  11235. @}
  11236. @end example
  11237.  
  11238. Note that the old-style variadic function definition has no fixed
  11239. parameter variables; all arguments must be obtained with
  11240. @code{va_arg}.
  11241.  
  11242. @node Compatible Types
  11243. @chapter Compatible Types
  11244. @cindex compatible types
  11245. @cindex types, compatible
  11246.  
  11247. Declaring a function or variable twice is valid in C only if the two
  11248. declarations specify @dfn{compatible} types.  In addition, some
  11249. operations on pointers require operands to have compatible target
  11250. types.
  11251.  
  11252. In C, two different primitive types are never compatible.  Likewise for
  11253. the defined types @code{struct}, @code{union} and @code{enum}: two
  11254. separately defined types are incompatible unless they are defined
  11255. exactly the same way.
  11256.  
  11257. However, there are a few cases where different types can be
  11258. compatible:
  11259.  
  11260. @itemize @bullet
  11261. @item
  11262. Every enumeration type is compatible with some integer type.  In GNU
  11263. C, the choice of integer type depends on the largest enumeration
  11264. value.
  11265.  
  11266. @c ??? Which one, in GCC?
  11267. @c ??? ... it varies, depending on the enum values. Testing on
  11268. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  11269. @c ??? then moves on to an 8-byte signed integer. These details
  11270. @c ??? might be platform-dependent, as the C standard says that even
  11271. @c ??? char could be used as an enum type, but it's at least true
  11272. @c ??? that GCC chooses a type that is at least large enough to
  11273. @c ??? hold the largest enum value.
  11274.  
  11275. @item
  11276. Array types are compatible if the element types are compatible
  11277. and the sizes (when specified) match.
  11278.  
  11279. @item
  11280. Pointer types are compatible if the pointer target types are
  11281. compatible.
  11282.  
  11283. @item
  11284. Function types that specify argument types are compatible if the
  11285. return types are compatible and the argument types are compatible,
  11286. argument by argument.  In addition, they must all agree in whether
  11287. they use @code{...} to allow additional arguments.
  11288.  
  11289. @item
  11290. Function types that don't specify argument types are compatible if the
  11291. return types are.
  11292.  
  11293. @item
  11294. Function types that specify the argument types are compatible with
  11295. function types that omit them, if the return types are compatible and
  11296. the specified argument types are unaltered by the argument promotions
  11297. (@pxref{Argument Promotions}).
  11298. @end itemize
  11299.  
  11300. In order for types to be compatible, they must agree in their type
  11301. qualifiers.  Thus, @code{const int} and @code{int} are incompatible.
  11302. It follows that @code{const int *} and @code{int *} are incompatible
  11303. too (they are pointers to types that are not compatible).
  11304.  
  11305. If two types are compatible ignoring the qualifiers, we call them
  11306. @dfn{nearly compatible}.  (If they are array types, we ignore
  11307. qualifiers on the element types.@footnote{This is a GNU C extension.})
  11308. Comparison of pointers is valid if the pointers' target types are
  11309. nearly compatible.  Likewise, the two branches of a conditional
  11310. expression may be pointers to nearly compatible target types.
  11311.  
  11312. If two types are compatible ignoring the qualifiers, and the first
  11313. type has all the qualifiers of the second type, we say the first is
  11314. @dfn{upward compatible} with the second.  Assignment of pointers
  11315. requires the assigned pointer's target type to be upward compatible
  11316. with the right operand (the new value)'s target type.
  11317.  
  11318. @node Type Conversions
  11319. @chapter Type Conversions
  11320. @cindex type conversions
  11321. @cindex conversions, type
  11322.  
  11323. C converts between data types automatically when that seems clearly
  11324. necessary.  In addition, you can convert explicitly with a @dfn{cast}.
  11325.  
  11326. @menu
  11327. * Explicit Type Conversion::     Casting a value from one type to another.
  11328. * Assignment Type Conversions::  Automatic conversion by assignment operation.
  11329. * Argument Promotions::          Automatic conversion of function parameters.
  11330. * Operand Promotions::           Automatic conversion of arithmetic operands.
  11331. * Common Type::                  When operand types differ, which one is used?
  11332. @end menu
  11333.  
  11334. @node Explicit Type Conversion
  11335. @section Explicit Type Conversion
  11336. @cindex cast
  11337. @cindex explicit type conversion
  11338.  
  11339. You can do explicit conversions using the unary @dfn{cast} operator,
  11340. which is written as a type designator (@pxref{Type Designators}) in
  11341. parentheses.  For example, @code{(int)} is the operator to cast to
  11342. type @code{int}.  Here's an example of using it:
  11343.  
  11344. @example
  11345. @{
  11346.   double d = 5.5;
  11347.  
  11348.   printf ("Floating point value: %f\n", d);
  11349.   printf ("Rounded to integer: %d\n", (int) d);
  11350. @}
  11351. @end example
  11352.  
  11353. Using @code{(int) d} passes an @code{int} value as argument to
  11354. @code{printf}, so you can print it with @samp{%d}.  Using just
  11355. @code{d} without the cast would pass the value as @code{double}.
  11356. That won't work at all with @samp{%d}; the results would be gibberish.
  11357.  
  11358. To divide one integer by another without rounding,
  11359. cast either of the integers to @code{double} first:
  11360.  
  11361. @example
  11362. (double) @var{dividend} / @var{divisor}
  11363. @var{dividend} / (double) @var{divisor}
  11364. @end example
  11365.  
  11366. It is enough to cast one of them, because that forces the common type
  11367. to @code{double} so the other will be converted automatically.
  11368.  
  11369. The valid cast conversions are:
  11370.  
  11371. @itemize @bullet
  11372. @item
  11373. One numerical type to another.
  11374.  
  11375. @item
  11376. One pointer type to another.
  11377. (Converting between pointers that point to functions
  11378. and pointers that point to data is not standard C.)
  11379.  
  11380. @item
  11381. A pointer type to an integer type.
  11382.  
  11383. @item
  11384. An integer type to a pointer type.
  11385.  
  11386. @item
  11387. To a union type, from the type of any alternative in the union
  11388. (@pxref{Unions}).  (This is a GNU extension.)
  11389.  
  11390. @item
  11391. Anything, to @code{void}.
  11392. @end itemize
  11393.  
  11394. @node Assignment Type Conversions
  11395. @section Assignment Type Conversions
  11396. @cindex assignment type conversions
  11397.  
  11398. Certain type conversions occur automatically in assignments
  11399. and certain other contexts.  These are the conversions
  11400. assignments can do:
  11401.  
  11402. @itemize @bullet
  11403. @item
  11404. Converting any numeric type to any other numeric type.
  11405.  
  11406. @item
  11407. Converting @code{void *} to any other pointer type
  11408. (except pointer-to-function types).
  11409.  
  11410. @item
  11411. Converting any other pointer type to @code{void *}.
  11412. (except pointer-to-function types).
  11413.  
  11414. @item
  11415. Converting 0 (a null pointer constant) to any pointer type.
  11416.  
  11417. @item
  11418. Converting any pointer type to @code{bool}.  (The result is
  11419. 1 if the pointer is not null.)
  11420.  
  11421. @item
  11422. Converting between pointer types when the left-hand target type is
  11423. upward compatible with the right-hand target type.  @xref{Compatible
  11424. Types}.
  11425. @end itemize
  11426.  
  11427. These type conversions occur automatically in certain contexts,
  11428. which are:
  11429.  
  11430. @itemize @bullet
  11431. @item
  11432. An assignment converts the type of the right-hand expression
  11433. to the type wanted by the left-hand expression.  For example,
  11434.  
  11435. @example
  11436. double i;
  11437. i = 5;
  11438. @end example
  11439.  
  11440. @noindent
  11441. converts 5 to @code{double}.
  11442.  
  11443. @item
  11444. A function call, when the function specifies the type for that
  11445. argument, converts the argument value to that type.  For example,
  11446.  
  11447. @example
  11448. void foo (double);
  11449. foo (5);
  11450. @end example
  11451.  
  11452. @noindent
  11453. converts 5 to @code{double}.
  11454.  
  11455. @item
  11456. A @code{return} statement converts the specified value to the type
  11457. that the function is declared to return.  For example,
  11458.  
  11459. @example
  11460. double
  11461. foo ()
  11462. @{
  11463.  return 5;
  11464. @}
  11465. @end example
  11466.  
  11467. @noindent
  11468. also converts 5 to @code{double}.
  11469. @end itemize
  11470.  
  11471. In all three contexts, if the conversion is impossible, that
  11472. constitutes an error.
  11473.  
  11474. @node Argument Promotions
  11475. @section Argument Promotions
  11476. @cindex argument promotions
  11477. @cindex promotion of arguments
  11478.  
  11479. When a function's definition or declaration does not specify the type
  11480. of an argument, that argument is passed without conversion in whatever
  11481. type it has, with these exceptions:
  11482.  
  11483. @itemize @bullet
  11484. @item
  11485. Some narrow numeric values are @dfn{promoted} to a wider type.  If the
  11486. expression is a narrow integer, such as @code{char} or @code{short},
  11487. the call converts it automatically to @code{int} (@pxref{Integer
  11488. Types}).@footnote{On an embedded controller where @code{char}
  11489. or @code{short} is the same width as @code{int}, @code{unsigned char}
  11490. or @code{unsigned short} promotes to @code{unsigned int}, but that
  11491. never occurs in GNU C on real computers.}
  11492.  
  11493. In this example, the expression @code{c} is passed as an @code{int}:
  11494.  
  11495. @example
  11496. char c = '$';
  11497.  
  11498. printf ("Character c is '%c'\n", c);
  11499. @end example
  11500.  
  11501. @item
  11502. If the expression
  11503. has type @code{float}, the call converts it automatically to
  11504. @code{double}.
  11505.  
  11506. @item
  11507. An array as argument is converted to a pointer to its zeroth element.
  11508.  
  11509. @item
  11510. A function name as argument is converted to a pointer to that function.
  11511. @end itemize
  11512.  
  11513. @node Operand Promotions
  11514. @section Operand Promotions
  11515. @cindex operand promotions
  11516.  
  11517. The operands in arithmetic operations undergo type conversion automatically.
  11518. These @dfn{operand promotions} are the same as the argument promotions
  11519. except without converting @code{float} to @code{double}.  In other words,
  11520. the operand promotions convert
  11521.  
  11522. @itemize @bullet
  11523. @item
  11524. @code{char} or @code{short} (whether signed or not) to @code{int}.
  11525.  
  11526. @item
  11527. an array to a pointer to its zeroth element, and
  11528.  
  11529. @item
  11530. a function name to a pointer to that function.
  11531. @end itemize
  11532.  
  11533. @node Common Type
  11534. @section Common Type
  11535. @cindex common type
  11536.  
  11537. Arithmetic binary operators (except the shift operators) convert their
  11538. operands to the @dfn{common type} before operating on them.
  11539. Conditional expressions also convert the two possible results to their
  11540. common type.  Here are the rules for determining the common type.
  11541.  
  11542. If one of the numbers has a floating-point type and the other is an
  11543. integer, the common type is that floating-point type.  For instance,
  11544.  
  11545. @example
  11546. 5.6 * 2   @result{} 11.2 /* @r{a @code{double} value} */
  11547. @end example
  11548.  
  11549. If both are floating point, the type with the larger range is the
  11550. common type.
  11551.  
  11552. If both are integers but of different widths, the common type
  11553. is the wider of the two.
  11554.  
  11555. If they are integer types of the same width, the common type is
  11556. unsigned if either operand is unsigned, and it's @code{long} if either
  11557. operand is @code{long}.  It's @code{long long} if either operand is
  11558. @code{long long}.
  11559.  
  11560. These rules apply to addition, subtraction, multiplication, division,
  11561. remainder, comparisons, and bitwise operations.  They also apply to
  11562. the two branches of a conditional expression, and to the arithmetic
  11563. done in a modifying assignment operation.
  11564.  
  11565. @node Scope
  11566. @chapter Scope
  11567. @cindex scope
  11568. @cindex block scope
  11569. @cindex function scope
  11570. @cindex function prototype scope
  11571.  
  11572. Each definition or declaration of an identifier is visible
  11573. in certain parts of the program, which is typically less than the whole
  11574. of the program.  The parts where it is visible are called its @dfn{scope}.
  11575.  
  11576. Normally, declarations made at the top-level in the source -- that is,
  11577. not within any blocks and function definitions -- are visible for the
  11578. entire contents of the source file after that point.  This is called
  11579. @dfn{file scope} (@pxref{File-Scope Variables}).
  11580.  
  11581. Declarations made within blocks of code, including within function
  11582. definitions, are visible only within those blocks.  This is called
  11583. @dfn{block scope}.  Here is an example:
  11584.  
  11585. @example
  11586. @group
  11587. void
  11588. foo (void)
  11589. @{
  11590.  int x = 42;
  11591. @}
  11592. @end group
  11593. @end example
  11594.  
  11595. @noindent
  11596. In this example, the variable @code{x} has block scope; it is visible
  11597. only within the @code{foo} function definition block.  Thus, other
  11598. blocks could have their own variables, also named @code{x}, without
  11599. any conflict between those variables.
  11600.  
  11601. A variable declared inside a subblock has a scope limited to
  11602. that subblock,
  11603.  
  11604. @example
  11605. @group
  11606. void
  11607. foo (void)
  11608. @{
  11609.  @{
  11610.    int x = 42;
  11611.  @}
  11612.  // @r{@code{x} is out of scope here.}
  11613. @}
  11614. @end group
  11615. @end example
  11616.  
  11617. If a variable declared within a block has the same name as a variable
  11618. declared outside of that block, the definition within the block
  11619. takes precedence during its scope:
  11620.  
  11621. @example
  11622. @group
  11623. int x = 42;
  11624.  
  11625. void
  11626. foo (void)
  11627. @{
  11628.   int x = 17;
  11629.   printf ("%d\n", x);
  11630. @}
  11631. @end group
  11632. @end example
  11633.  
  11634. @noindent
  11635. This prints 17, the value of the variable @code{x} declared in the
  11636. function body block, rather than the value of the variable @code{x} at
  11637. file scope.  We say that the inner declaration of @code{x}
  11638. @dfn{shadows} the outer declaration, for the extent of the inner
  11639. declaration's scope.
  11640.  
  11641. A declaration with block scope can be shadowed by another declaration
  11642. with the same name in a subblock.
  11643.  
  11644. @example
  11645. @group
  11646. void
  11647. foo (void)
  11648. @{
  11649.  char *x = "foo";
  11650.  @{
  11651.    int x = 42;
  11652.    @r{@dots{}}
  11653.    exit (x / 6);
  11654.  @}
  11655. @}
  11656. @end group
  11657. @end example
  11658.  
  11659. A function parameter's scope is the entire function body, but it can
  11660. be shadowed.  For example:
  11661.  
  11662. @example
  11663. @group
  11664. int x = 42;
  11665.  
  11666. void
  11667. foo (int x)
  11668. @{
  11669.   printf ("%d\n", x);
  11670. @}
  11671. @end group
  11672. @end example
  11673.  
  11674. @noindent
  11675. This prints the value of @code{x} the function parameter, rather than
  11676. the value of the file-scope variable @code{x}.  However,
  11677.  
  11678. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  11679. is visible for the whole of the containing function body, both before
  11680. and after the label declaration:
  11681.  
  11682. @example
  11683. @group
  11684. void
  11685. foo (void)
  11686. @{
  11687.  @r{@dots{}}
  11688.  goto bar;
  11689.  @r{@dots{}}
  11690.  @{  // @r{Subblock does not affect labels.}
  11691.    bar:
  11692.    @r{@dots{}}
  11693.  @}
  11694.  goto bar;
  11695. @}
  11696. @end group
  11697. @end example
  11698.  
  11699. Except for labels, a declared identifier is not
  11700. visible to code before its declaration.  For example:
  11701.  
  11702. @example
  11703. @group
  11704. int x = 5;
  11705. int y = x + 10;
  11706. @end group
  11707. @end example
  11708.  
  11709. @noindent
  11710. will work, but:
  11711.  
  11712. @example
  11713. @group
  11714. int x = y + 10;
  11715. int y = 5;
  11716. @end group
  11717. @end example
  11718.  
  11719. @noindent
  11720. cannot refer to the variable @code{y} before its declaration.
  11721.  
  11722. @include cpp.texi
  11723.  
  11724. @node    Integers in Depth
  11725. @chapter Integers in Depth
  11726.  
  11727. This chapter explains the machine-level details of integer types: how
  11728. they are represented as bits in memory, and the range of possible
  11729. values for each integer type.
  11730.  
  11731. @menu
  11732. * Integer Representations::      How integer values appear in memory.
  11733. * Maximum and Minimum Values::   Value ranges of integer types.
  11734. @end menu
  11735.  
  11736. @node Integer Representations
  11737. @section Integer Representations
  11738.  
  11739. @cindex integer representations
  11740. @cindex representation of integers
  11741.  
  11742. Modern computers store integer values as binary (base-2) numbers that
  11743. occupy a single unit of storage, typically either as an 8-bit
  11744. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  11745. possibly, a 64-bit @code{long long int}.  Whether a @code{long int} is
  11746. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  11747. any of these types could have some other size, bit it's not worth even
  11748. a minute to cater to that possibility.  It never happens on
  11749. GNU/Linux.}
  11750.  
  11751. @cindex @code{CHAR_BIT}
  11752. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  11753. of bits in type @code{char}.  On any real operating system, the value
  11754. is 8.
  11755.  
  11756. The fixed sizes of numeric types necessarily limits their @dfn{range
  11757. of values}, and the particular encoding of integers decides what that
  11758. range is.
  11759.  
  11760. @cindex two's-complement representation
  11761. For unsigned integers, the entire space is used to represent a
  11762. nonnegative value.  Signed integers are stored using
  11763. @dfn{two's-complement representation}: a signed integer with @var{n}
  11764. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  11765. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive.  The leftmost, or
  11766. high-order, bit is called the @dfn{sign bit}.
  11767.  
  11768. @c ??? Needs correcting
  11769.  
  11770. There is only one value that means zero, and the most negative number
  11771. lacks a positive counterpart.  As a result, negating that number
  11772. causes overflow; in practice, its result is that number back again.
  11773. For example, a two's-complement signed 8-bit integer can represent all
  11774. decimal numbers from @minus{}128 to +127.  We will revisit that
  11775. peculiarity shortly.
  11776.  
  11777. Decades ago, there were computers that didn't use two's-complement
  11778. representation for integers (@pxref{Integers in Depth}), but they are
  11779. long gone and not worth any effort to support.
  11780.  
  11781. @c ??? Is this duplicate?
  11782.  
  11783. When an arithmetic operation produces a value that is too big to
  11784. represent, the operation is said to @dfn{overflow}.  In C, integer
  11785. overflow does not interrupt the control flow or signal an error.
  11786. What it does depends on signedness.
  11787.  
  11788. For unsigned arithmetic, the result of an operation that overflows is
  11789. the @var{n} low-order bits of the correct value.  If the correct value
  11790. is representable in @var{n} bits, that is always the result;
  11791. thus we often say that ``integer arithmetic is exact,'' omitting the
  11792. crucial qualifying phrase ``as long as the exact result is
  11793. representable.''
  11794.  
  11795. In principle, a C program should be written so that overflow never
  11796. occurs for signed integers, but in GNU C you can specify various ways
  11797. of handling such overflow (@pxref{Integer Overflow}).
  11798.  
  11799. Integer representations are best understood by looking at a table for
  11800. a tiny integer size; here are the possible values for an integer with
  11801. three bits:
  11802.  
  11803. @multitable @columnfractions .25 .25 .25 .25
  11804. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  11805. @item 0 @tab 0 @tab 000 @tab 000 (0)
  11806. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  11807. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  11808. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  11809. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  11810. @item 5 @tab -3 @tab 101 @tab 011 (3)
  11811. @item 6 @tab -2 @tab 110 @tab 010 (2)
  11812. @item 7 @tab -1 @tab 111 @tab 001 (1)
  11813. @end multitable
  11814.  
  11815. The parenthesized decimal numbers in the last column represent the
  11816. signed meanings of the two's-complement of the line's value.  Recall
  11817. that, in two's-complement encoding, the high-order bit is 0 when
  11818. the number is nonnegative.
  11819.  
  11820. We can now understand the peculiar behavior of negation of the
  11821. most negative two's-complement integer: start with 0b100,
  11822. invert the bits to get 0b011, and add 1: we get
  11823. 0b100, the value we started with.
  11824.  
  11825. We can also see overflow behavior in two's-complement:
  11826.  
  11827. @example
  11828. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  11829. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  11830. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  11831. @end example
  11832.  
  11833. @noindent
  11834. A sum of two nonnegative signed values that overflows has a 1 in the
  11835. sign bit, so the exact positive result is truncated to a negative
  11836. value.
  11837.  
  11838. @c =====================================================================
  11839.  
  11840. @node Maximum and Minimum Values
  11841. @section Maximum and Minimum Values
  11842. @cindex maximum integer values
  11843. @cindex minimum integer values
  11844. @cindex integer ranges
  11845. @cindex ranges of integer types
  11846. @findex INT_MAX
  11847. @findex UINT_MAX
  11848. @findex SHRT_MAX
  11849. @findex LONG_MAX
  11850. @findex LLONG_MAX
  11851. @findex USHRT_MAX
  11852. @findex ULONG_MAX
  11853. @findex ULLONG_MAX
  11854. @findex CHAR_MAX
  11855. @findex SCHAR_MAX
  11856. @findex UCHAR_MAX
  11857.  
  11858. For each primitive integer type, there is a standard macro defined in
  11859. @file{limits.h} that gives the largest value that type can hold.  For
  11860. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  11861. On a 32-bit computer, that is equal to 2,147,483,647.  The
  11862. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  11863. 32-bit computer is equal to 4,294,967,295.  Likewise, there are
  11864. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  11865. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  11866. @code{ULLONG_MAX}.
  11867.  
  11868. Since there are three ways to specify a @code{char} type, there are
  11869. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  11870. @code{UCHAR_MAX}.
  11871.  
  11872. For each type that is or might be signed, there is another symbol that
  11873. gives the minimum value it can hold.  (Just replace @code{MAX} with
  11874. @code{MIN} in the names listed above.)  There is no minimum limit
  11875. symbol for types specified with @code{unsigned} because the
  11876. minimum for them is universally zero.
  11877.  
  11878. @code{INT_MIN} is not the negative of @code{INT_MAX}.  In
  11879. two's-complement representation, the most negative number is 1 less
  11880. than the negative of the most positive number.  Thus, @code{INT_MIN}
  11881. on a 32-bit computer has the value @minus{}2,147,483,648.  You can't
  11882. actually write the value that way in C, since it would overflow.
  11883. That's a good reason to use @code{INT_MIN} to specify
  11884. that value.  Its definition is written to avoid overflow.
  11885.  
  11886. @include fp.texi
  11887.  
  11888. @node Compilation
  11889. @chapter Compilation
  11890. @cindex object file
  11891. @cindex compilation module
  11892. @cindex make rules
  11893.  
  11894. Early in the manual we explained how to compile a simple C program
  11895. that consists of a single source file (@pxref{Compile Example}).
  11896. However, we handle only short programs that way.  A typical C program
  11897. consists of many source files, each of which is a separate
  11898. @dfn{compilation module}---meaning that it has to be compiled
  11899. separately.
  11900.  
  11901. The full details of how to compile with GCC are documented in xxxx.
  11902. @c ??? ref
  11903. Here we give only a simple introduction.
  11904.  
  11905. These are the commands to compile two compilation modules,
  11906. @file{foo.c} and @file{bar.c}, with a command for each module:
  11907.  
  11908. @example
  11909. gcc -c -O -g foo.c
  11910. gcc -c -O -g bar.c
  11911. @end example
  11912.  
  11913. @noindent
  11914. In these commands, @option{-g} says to generate debugging information,
  11915. @option{-O} says to do some optimization, and @option{-c} says to put
  11916. the compiled code for that module into a corresponding @dfn{object
  11917. file} and go no further.  The object file for @file{foo.c} is called
  11918. @file{foo.o}, and so on.
  11919.  
  11920. If you wish, you can specify the additional options @option{-Wformat
  11921. -Wparenthesis -Wstrict-prototypes}, which request additional warnings.
  11922.  
  11923. One reason to divide a large program into multiple compilation modules
  11924. is to control how each module can access the internals of the others.
  11925. When a module declares a function or variable @code{extern}, other
  11926. modules can access it.  The other functions and variables in
  11927. a module can't be accessed from outside that module.
  11928.  
  11929. The other reason for using multiple modules is so that changing
  11930. one source file does not require recompiling all of them in order
  11931. to try the modified program.  Dividing a large program into many
  11932. substantial modules in this way typically makes recompilation much faster.
  11933.  
  11934. @cindex linking object files
  11935. After you compile all the program's modules, in order to run the
  11936. program you must @dfn{link} the object files into a combined
  11937. executable, like this:
  11938.  
  11939. @example
  11940. gcc -o foo foo.o bar.o
  11941. @end example
  11942.  
  11943. @noindent
  11944. In this command, @option{-o foo} species the file name for the
  11945. executable file, and the other arguments are the object files to link.
  11946. Always specify the executable file name in a command that generates
  11947. one.
  11948.  
  11949. Normally we don't run any of these commands directly.  Instead we
  11950. write a set of @dfn{make rules} for the program, then use the
  11951. @command{make} program to recompile only the source files that need to
  11952. be recompiled.
  11953.  
  11954. @c ??? ref to make manual
  11955.  
  11956. @node Directing Compilation
  11957. @chapter Directing Compilation
  11958.  
  11959. This chapter describes C constructs that don't alter the program's
  11960. meaning @emph{as such}, but rather direct the compiler how to treat
  11961. some aspects of the program.
  11962.  
  11963. @menu
  11964. * Pragmas::                      Controling compilation of some constructs.
  11965. * Static Assertions::            Compile-time tests for conditions.
  11966. @end menu
  11967.  
  11968. @node Pragmas
  11969. @section Pragmas
  11970.  
  11971. A @dfn{pragma} is an annotation in a program that gives direction to
  11972. the compiler.
  11973.  
  11974. @menu
  11975. * Pragma Basics::         Pragma syntax and usage.
  11976. * Severity Pragmas::      Settings for compile-time pragma output.
  11977. * Optimization Pragmas::  Controlling optimizations.
  11978. @end menu
  11979.  
  11980. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  11981.  
  11982. @node Pragma Basics
  11983. @subsection Pragma Basics
  11984.  
  11985. C defines two syntactical forms for pragmas, the line form and the
  11986. token form.  You can write any pragma in either form, with the same
  11987. meaning.
  11988.  
  11989. The line form is a line in the source code, like this:
  11990.  
  11991. @example
  11992. #pragma @var{line}
  11993. @end example
  11994.  
  11995. @noindent
  11996. The line pragma has no effect on the parsing of the lines around it.
  11997. This form has the drawback that it can't be generated by a macro expansion.
  11998.  
  11999. The token form is a series of tokens; it can appear anywhere in the
  12000. program between the other tokens.
  12001.  
  12002. @example
  12003. _Pragma (@var{stringconstant})
  12004. @end example
  12005.  
  12006. @noindent
  12007. The pragma has no effect on the syntax of the tokens that surround it;
  12008. thus, here's a pragma in the middle of an @code{if} statement:
  12009.  
  12010. @example
  12011. if _Pragma ("hello") (x > 1)
  12012. @end example
  12013.  
  12014. @noindent
  12015. However, that's an unclear thing to do; for the sake of
  12016. understandability, it is better to put a pragma on a line by itself
  12017. and not embedded in the middle of another construct.
  12018.  
  12019. Both forms of pragma have a textual argument.  In a line pragma, the
  12020. text is the rest of the line.  The textual argument to @code{_Pragma}
  12021. uses the same syntax as a C string constant: surround the text with
  12022. two @samp{"} characters, and add a backslash before each @samp{"} or
  12023. @samp{\} character in it.
  12024.  
  12025. With either syntax, the textual argument specifies what to do.
  12026. It begins with one or several words that specify the operation.
  12027. If the compiler does not recognize them, it ignores the pragma.
  12028.  
  12029. Here are the pragma operations supported in GNU C@.
  12030.  
  12031. @c ??? Verify font for []
  12032. @table @code
  12033. @item #pragma GCC dependency "@var{file}" [@var{message}]
  12034. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  12035. Declares that the current source file depends on @var{file}, so GNU C
  12036. compares the file times and gives a warning if @var{file} is newer
  12037. than the current source file.
  12038.  
  12039. This directive searches for @var{file} the way @code{#include}
  12040. searches for a non-system header file.
  12041.  
  12042. If @var{message} is given, the warning message includes that text.
  12043.  
  12044. Examples:
  12045.  
  12046. @example
  12047. #pragma GCC dependency "parse.y"
  12048. _pragma ("GCC dependency \"/usr/include/time.h\" \
  12049. rerun fixincludes")
  12050. @end example
  12051.  
  12052. @item #pragma GCC poison @var{identifiers}
  12053. @itemx _Pragma ("GCC poison @var{identifiers}")
  12054. Poisons the identifiers listed in @var{identifiers}.
  12055.  
  12056. This is useful to make sure all mention of @var{identifiers} has been
  12057. deleted from the program and that no reference to them creeps back in.
  12058. If any of those identifiers appears anywhere in the source after the
  12059. directive, it causes a compilation error.  For example,
  12060.  
  12061. @example
  12062. #pragma GCC poison printf sprintf fprintf
  12063. sprintf(some_string, "hello");
  12064. @end example
  12065.  
  12066. @noindent
  12067. generates an error.
  12068.  
  12069. If a poisoned identifier appears as part of the expansion of a macro
  12070. that was defined before the identifier was poisoned, it will @emph{not}
  12071. cause an error.  Thus, system headers that define macros that use
  12072. the identifier will not cause errors.
  12073.  
  12074. For example,
  12075.  
  12076. @example
  12077. #define strrchr rindex
  12078. _Pragma ("GCC poison rindex")
  12079. strrchr(some_string, 'h');
  12080. @end example
  12081.  
  12082. @noindent
  12083. does not cause a compilation error.
  12084.  
  12085. @item #pragma GCC system_header
  12086. @itemx _Pragma ("GCC system_header")
  12087. Specify treating the rest of the current source file as if it came
  12088. from a system header file.  @xref{System Headers, System Headers,
  12089. System Headers, gcc, Using the GNU Compiler Collection}.
  12090.  
  12091. @item #pragma GCC warning @var{message}
  12092. @itemx _Pragma ("GCC warning @var{message}")
  12093. Equivalent to @code{#warning}.  Its advantage is that the
  12094. @code{_Pragma} form can be included in a macro definition.
  12095.  
  12096. @item #pragma GCC error @var{message}
  12097. @itemx _Pragma ("GCC error @var{message}")
  12098. Equivalent to @code{#error}.  Its advantage is that the
  12099. @code{_Pragma} form can be included in a macro definition.
  12100.  
  12101. @item #pragma GCC message @var{message}
  12102. @itemx _Pragma ("GCC message @var{message}")
  12103. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  12104. informational message, and could be used to include additional warning
  12105. or error text without triggering more warnings or errors.  (Note that
  12106. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  12107. @samp{GCC} as part of the pragma.)
  12108. @end table
  12109.  
  12110. @node Severity Pragmas
  12111. @subsection Severity Pragmas
  12112.  
  12113. These pragmas control the severity of classes of diagnostics.
  12114. You can specify the class of diagnostic with the GCC option that causes
  12115. those diagnostics to be generated.
  12116.  
  12117. @table @code
  12118. @item #pragma GCC diagnostic error @var{option}
  12119. @itemx _Pragma ("GCC diagnostic error @var{option}")
  12120. For code following this pragma, treat diagnostics of the variety
  12121. specified by @var{option} as errors.  For example:
  12122.  
  12123. @example
  12124. _Pragma ("GCC diagnostic error -Wformat")
  12125. @end example
  12126.  
  12127. @noindent
  12128. specifies to treat diagnostics enabled by the @var{-Wformat} option
  12129. as errors rather than warnings.
  12130.  
  12131. @item #pragma GCC diagnostic warning @var{option}
  12132. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  12133. For code following this pragma, treat diagnostics of the variety
  12134. specified by @var{option} as warnings.  This overrides the
  12135. @var{-Werror} option which says to treat warnings as errors.
  12136.  
  12137. @item #pragma GCC diagnostic ignore @var{option}
  12138. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  12139. For code following this pragma, refrain from reporting any diagnostics
  12140. of the variety specified by @var{option}.
  12141.  
  12142. @item #pragma GCC diagnostic push
  12143. @itemx _Pragma ("GCC diagnostic push")
  12144. @itemx #pragma GCC diagnostic pop
  12145. @itemx _Pragma ("GCC diagnostic pop")
  12146. These pragmas maintain a stack of states for severity settings.
  12147. @samp{GCC diagnostic push} saves the current settings on the stack,
  12148. and @samp{GCC diagnostic pop} pops the last stack item and restores
  12149. the current settings from that.
  12150.  
  12151. @samp{GCC diagnostic pop} when the severity setting stack is empty
  12152. restores the settings to what they were at the start of compilation.
  12153.  
  12154. Here is an example:
  12155.  
  12156. @example
  12157. _Pragma ("GCC diagnostic error -Wformat")
  12158.  
  12159. /* @r{@option{-Wformat} messages treated as errors. } */
  12160.  
  12161. _Pragma ("GCC diagnostic push")
  12162. _Pragma ("GCC diagnostic warning -Wformat")
  12163.  
  12164. /* @r{@option{-Wformat} messages treated as warnings. } */
  12165.  
  12166. _Pragma ("GCC diagnostic push")
  12167. _Pragma ("GCC diagnostic ignored -Wformat")
  12168.  
  12169. /* @r{@option{-Wformat} messages suppressed. } */
  12170.  
  12171. _Pragma ("GCC diagnostic pop")
  12172.  
  12173. /* @r{@option{-Wformat} messages treated as warnings again. } */
  12174.  
  12175. _Pragma ("GCC diagnostic pop")
  12176.  
  12177. /* @r{@option{-Wformat} messages treated as errors again. } */
  12178.  
  12179. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  12180. _Pragma ("GCC diagnostic pop")
  12181.  
  12182. /* @r{@option{-Wformat} messages treated once again}
  12183.   @r{as specified by the GCC command-line options.}  */
  12184. @end example
  12185. @end table
  12186.  
  12187. @node Optimization Pragmas
  12188. @subsection Optimization Pragmas
  12189.  
  12190. These pragmas enable a particular optimization for specific function
  12191. definitions.  The settings take effect at the end of a function
  12192. definition, so the clean place to use these pragmas is between
  12193. function definitions.
  12194.  
  12195. @table @code
  12196. @item #pragma GCC optimize @var{optimization}
  12197. @itemx _Pragma ("GCC optimize @var{optimization}")
  12198. These pragmas enable the optimization @var{optimization} for the
  12199. following functions.  For example,
  12200.  
  12201. @example
  12202. _Pragma ("GCC optimize -fforward-propagate")
  12203. @end example
  12204.  
  12205. @noindent
  12206. says to apply the @samp{forward-propagate} optimization to all
  12207. following function definitions.  Specifying optimizations for
  12208. individual functions, rather than for the entire program, is rare but
  12209. can be useful for getting around a bug in the compiler.
  12210.  
  12211. If @var{optimization} does not correspond to a defined optimization
  12212. option, the pragma is erroneous.  To turn off an optimization, use the
  12213. corresponding @samp{-fno-} option, such as
  12214. @samp{-fno-forward-propagate}.
  12215.  
  12216. @item #pragma GCC target @var{optimizations}
  12217. @itemx _Pragma ("GCC target @var{optimizations}")
  12218. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  12219. used for platform-specific optimizations.  Thus,
  12220.  
  12221. @example
  12222. _Pragma ("GCC target popcnt")
  12223. @end example
  12224.  
  12225. @noindent
  12226. activates the optimization @samp{popcnt} for all
  12227. following function definitions.  This optimization is supported
  12228. on a few common targets but not on others.
  12229.  
  12230. @item #pragma GCC push_options
  12231. @itemx _Pragma ("GCC push_options")
  12232. The @samp{push_options} pragma saves on a stack the current settings
  12233. specified with the @samp{target} and @samp{optimize} pragmas.
  12234.  
  12235. @item #pragma GCC pop_options
  12236. @itemx _Pragma ("GCC pop_options")
  12237. The @samp{pop_options} pragma pops saved settings from that stack.
  12238.  
  12239. Here's an example of using this stack.
  12240.  
  12241. @example
  12242. _Pragma ("GCC push_options")
  12243. _Pragma ("GCC optimize forward-propagate")
  12244.  
  12245. /* @r{Functions to compile}
  12246.   @r{with the @code{forward-propagate} optimization.} */
  12247.  
  12248. _Pragma ("GCC pop_options")
  12249. /* @r{Ends enablement of @code{forward-propagate}.} */
  12250. @end example
  12251.  
  12252. @item #pragma GCC reset_options
  12253. @itemx _Pragma ("GCC reset_options")
  12254. Clears all pragma-defined @samp{target} and @samp{optimize}
  12255. optimization settings.
  12256. @end table
  12257.  
  12258. @node Static Assertions
  12259. @section Static Assertions
  12260. @cindex static assertions
  12261. @findex _Static_assert
  12262.  
  12263. You can add compiler-time tests for necessary conditions into your
  12264. code using @code{_Static_assert}.  This can be useful, for example, to
  12265. check that the compilation target platform supports the type sizes
  12266. that the code expects.  For example,
  12267.  
  12268. @example
  12269. _Static_assert ((sizeof (long int) >= 8),
  12270.    "long int needs to be at least 8 bytes");
  12271. @end example
  12272.  
  12273. @noindent
  12274. reports a compile-time error if compiled on a system with long
  12275. integers smaller than 8 bytes, with @samp{long int needs to be at
  12276. least 8 bytes} as the error message.
  12277.  
  12278. Since calls @code{_Static_assert} are processed at compile time, the
  12279. expression must be computable at compile time and the error message
  12280. must be a literal string.  The expression can refer to the sizes of
  12281. variables, but can't refer to their values.  For example, the
  12282. following static assertion is invalid for two reasons:
  12283.  
  12284. @example
  12285. char *error_message
  12286.  = "long int needs to be at least 8 bytes";
  12287. int size_of_long_int = sizeof (long int);
  12288.  
  12289. _Static_assert (size_of_long_int == 8, error_message);
  12290. @end example
  12291.  
  12292. @noindent
  12293. The expression @code{size_of_long_int == 8} isn't computable at
  12294. compile time, and the error message isn't a literal string.
  12295.  
  12296. You can, though, use preprocessor definition values with
  12297. @code{_Static_assert}:
  12298.  
  12299. @example
  12300. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  12301. at least 8 bytes"
  12302.  
  12303. _Static_assert ((sizeof (long int) == 8),
  12304.  LONG_INT_ERROR_MESSAGE);
  12305. @end example
  12306.  
  12307. Static assertions are permitted wherever a statement or declaration is
  12308. permitted, including at top level in the file, and also inside the
  12309. definition of a type.
  12310.  
  12311. @example
  12312. union y
  12313. @{
  12314.  int i;
  12315.  int *ptr;
  12316.  _Static_assert (sizeof (int *) == sizeof (int),
  12317.           "Pointer and int not same size");
  12318. @};
  12319. @end example
  12320.  
  12321. @node Type Alignment
  12322. @appendix Type Alignment
  12323. @cindex type alignment
  12324. @cindex alignment of type
  12325. @findex _Alignof
  12326. @findex __alignof__
  12327.  
  12328. Code for device drivers and other communication with low-level
  12329. hardware sometimes needs to be concerned with the alignment of
  12330. data objects in memory.
  12331.  
  12332. Each data type has a required @dfn{alignment}, always a power of 2,
  12333. that says at which memory addresses an object of that type can validly
  12334. start.  A valid address for the type must be a multiple of its
  12335. alignment.  If a type's alignment is 1, that means it can validly
  12336. start at any address.  If a type's alignment is 2, that means it can
  12337. only start at an even address.  If a type's alignment is 4, that means
  12338. it can only start at an address that is a multiple of 4.
  12339.  
  12340. The alignment of a type (except @code{char}) can vary depending on the
  12341. kind of computer in use.  To refer to the alignment of a type in a C
  12342. program, use @code{_Alignof}, whose syntax parallels that of
  12343. @code{sizeof}.  Like @code{sizeof}, @code{_Alignof} is a compile-time
  12344. operation, and it doesn't compute the value of the expression used
  12345. as its argument.
  12346.  
  12347. Nominally, each integer and floating-point type has an alignment equal to
  12348. the largest power of 2 that divides its size.  Thus, @code{int} with
  12349. size 4 has a nominal alignment of 4, and @code{long long int} with
  12350. size 8 has a nominal alignment of 8.
  12351.  
  12352. However, each kind of computer generally has a maximum alignment, and
  12353. no type needs more alignment than that.  If the computer's maximum
  12354. alignment is 4 (which is common), then no type's alignment is more
  12355. than 4.
  12356.  
  12357. The size of any type is always a multiple of its alignment; that way,
  12358. in an array whose elements have that type, all the elements are
  12359. properly aligned if the first one is.
  12360.  
  12361. These rules apply to all real computers today, but some embedded
  12362. controllers have odd exceptions.  We don't have references to cite for
  12363. them.
  12364. @c We can't cite a nonfree manual as documentation.
  12365.  
  12366. Ordinary C code guarantees that every object of a given type is in
  12367. fact aligned as that type requires.
  12368.  
  12369. If the operand of @code{_Alignof} is a structure field, the value
  12370. is the alignment it requires.  It may have a greater alignment by
  12371. coincidence, due to the other fields, but @code{_Alignof} is not
  12372. concerned about that.  @xref{Structures}.
  12373.  
  12374. Older versions of GNU C used the keyword @code{__alignof__} for this,
  12375. but now that the feature has been standardized, it is better
  12376. to use the standard keyword @code{_Alignof}.
  12377.  
  12378. @findex _Alignas
  12379. @findex __aligned__
  12380. You can explicitly specify an alignment requirement for a particular
  12381. variable or structure field by adding @code{_Alignas
  12382. (@var{alignment})} to the declaration, where @var{alignment} is a
  12383. power of 2 or a type name.  For instance:
  12384.  
  12385. @example
  12386. char _Alignas (8) x;
  12387. @end example
  12388.  
  12389. @noindent
  12390. or
  12391.  
  12392. @example
  12393. char _Alignas (double) x;
  12394. @end example
  12395.  
  12396. @noindent
  12397. specifies that @code{x} must start on an address that is a multiple of
  12398. 8.  However, if @var{alignment} exceeds the maximum alignment for the
  12399. machine, that maximum is how much alignment @code{x} will get.
  12400.  
  12401. The older GNU C syntax for this feature looked like
  12402. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  12403. declaration, and was added after the variable.  For instance:
  12404.  
  12405. @example
  12406. char x __attribute__ ((__aligned__ 8));
  12407. @end example
  12408.  
  12409. @xref{Attributes}.
  12410.  
  12411. @node Aliasing
  12412. @appendix Aliasing
  12413. @cindex aliasing (of storage)
  12414. @cindex pointer type conversion
  12415. @cindex type conversion, pointer
  12416.  
  12417. We have already presented examples of casting a @code{void *} pointer
  12418. to another pointer type, and casting another pointer type to
  12419. @code{void *}.
  12420.  
  12421. One common kind of pointer cast is guaranteed safe: casting the value
  12422. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  12423. Allocation}).  It is safe because these functions do not save the
  12424. pointer anywhere else; the only way the program will access the newly
  12425. allocated memory is via the pointer just returned.
  12426.  
  12427. In fact, C allows casting any pointer type to any other pointer type.
  12428. Using this to access the same place in memory using two
  12429. different data types is called @dfn{aliasing}.
  12430.  
  12431. Aliasing is necessary in some programs that do sophisticated memory
  12432. management, such as GNU Emacs, but most C programs don't need to do
  12433. aliasing.  When it isn't needed, @strong{stay away from it!}  To do
  12434. aliasing correctly requires following the rules stated below.
  12435. Otherwise, the aliasing may result in malfunctions when the program
  12436. runs.
  12437.  
  12438. The rest of this appendix explains the pitfalls and rules of aliasing.
  12439.  
  12440. @menu
  12441. * Aliasing Alignment::   Memory alignment considerations for
  12442.                           casting between pointer types.
  12443. * Aliasing Length::      Type size considerations for
  12444.                           casting between pointer types.
  12445. * Aliasing Type Rules::  Even when type alignment and size matches,
  12446.                           aliasing can still have surprising results.
  12447.  
  12448. @end menu
  12449.  
  12450. @node Aliasing Alignment
  12451. @appendixsection Aliasing and Alignment
  12452.  
  12453. In order for a type-converted pointer to be valid, it must have the
  12454. alignment that the new pointer type requires.  For instance, on most
  12455. computers, @code{int} has alignment 4; the address of an @code{int}
  12456. must be a multiple of 4.  However, @code{char} has alignment 1, so the
  12457. address of a @code{char} is usually not a multiple of 4.  Taking the
  12458. address of such a @code{char} and casting it to @code{int *} probably
  12459. results in an invalid pointer.  Trying to dereference it may cause a
  12460. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  12461.  
  12462. @example
  12463. foo ()
  12464. @{
  12465.  char i[4];
  12466.  int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  12467.  return *p;              /* @r{Crash!} */
  12468. @}
  12469. @end example
  12470.  
  12471. This requirement is never a problem when casting the return value
  12472. of @code{malloc} because that function always returns a pointer
  12473. with as much alignment as any type can require.
  12474.  
  12475. @node Aliasing Length
  12476. @appendixsection Aliasing and Length
  12477.  
  12478. When converting a pointer to a different pointer type, make sure the
  12479. object it really points to is at least as long as the target of the
  12480. converted pointer.  For instance, suppose @code{p} has type @code{int
  12481. *} and it's cast as follows:
  12482.  
  12483. @example
  12484. int *p;
  12485.  
  12486. struct
  12487.  @{
  12488.    double d, e, f;
  12489.  @} foo;
  12490.  
  12491. struct foo *q = (struct foo *)p;
  12492.  
  12493. q->f = 5.14159;
  12494. @end example
  12495.  
  12496. @noindent
  12497. the value @code{q->f} will run past the end of the @code{int} that
  12498. @code{p} points to.  If @code{p} was initialized to the start of an
  12499. array of type @code{int[6]}, the object is long enough for three
  12500. @code{double}s.  But if @code{p} points to something shorter,
  12501. @code{q->f} will run on beyond the end of that, overlaying some other
  12502. data.  Storing that will garble that other data.  Or it could extend
  12503. past the end of memory space and cause a @code{SIGSEGV} signal
  12504. (@pxref{Signals}).
  12505.  
  12506. @node Aliasing Type Rules
  12507. @appendixsection Type Rules for Aliasing
  12508.  
  12509. C code that converts a pointer to a different pointer type can use the
  12510. pointers to access the same memory locations with two different data
  12511. types.  If the same address is accessed with different types in a
  12512. single control thread, optimization can make the code do surprising
  12513. things (in effect, make it malfunction).
  12514.  
  12515. Here's a concrete example where aliasing that can change the code's
  12516. behavior when it is optimized.  We assume that @code{float} is 4 bytes
  12517. long, like @code{int}, and so is every pointer.  Thus, the structures
  12518. @code{struct a} and @code{struct b} are both 8 bytes.
  12519.  
  12520. @example
  12521. #include <stdio.h>
  12522. struct a @{ int size; char *data; @};
  12523. struct b @{ float size; char *data; @};
  12524.  
  12525. void sub (struct a *p, struct b *q)
  12526. @{
  12527.   int x;
  12528.   p->size = 0;
  12529.   q->size = 1;
  12530.   x = p->size;
  12531.   printf("x       =%d\n", x);
  12532.   printf("p->size =%d\n", (int)p->size);
  12533.   printf("q->size =%d\n", (int)q->size);
  12534. @}
  12535.  
  12536. int main(void)
  12537. @{
  12538.   struct a foo;
  12539.   struct a *p = &foo;
  12540.   struct b *q = (struct b *) &foo;
  12541.  
  12542.   sub (p, q);
  12543. @}
  12544. @end example
  12545.  
  12546. This code works as intended when compiled without optimization.  All
  12547. the operations are carried out sequentially as written.  The code
  12548. sets @code{x} to @code{p->size}, but what it actually gets is the
  12549. bits of the floating point number 1, as type @code{int}.
  12550.  
  12551. However, when optimizing, the compiler is allowed to assume
  12552. (mistakenly, here) that @code{q} does not point to the same storage as
  12553. @code{p}, because their data types are not allowed to alias.
  12554.  
  12555. From this assumption, the compiler can deduce (falsely, here) that the
  12556. assignment into @code{q->size} has no effect on the value of
  12557. @code{p->size}, which must therefore still be 0.  Thus, @code{x} will
  12558. be set to 0.
  12559.  
  12560. GNU C, following the C standard, @emph{defines} this optimization as
  12561. legitimate.  Code that misbehaves when optimized following these rules
  12562. is, by definition, incorrect C code.
  12563.  
  12564. The rules for storage aliasing in C are based on the two data types:
  12565. the type of the object, and the type it is accessed through.  The
  12566. rules permit accessing part of a storage object of type @var{t} using
  12567. only these types:
  12568.  
  12569. @itemize @bullet
  12570. @item
  12571. @var{t}.
  12572.  
  12573. @item
  12574. A type compatible with @var{t}.  @xref{Compatible Types}.
  12575.  
  12576. @item
  12577. A signed or unsigned version of one of the above.
  12578.  
  12579. @item
  12580. A qualifed version of one of the above.
  12581. @xref{Type Qualifiers}.
  12582.  
  12583. @item
  12584. An array, structure (@pxref{Structures}), or union type
  12585. (@code{Unions}) that contains one of the above, either directly as a
  12586. field or through multiple levels of fields.  If @var{t} is
  12587. @code{double}, this would include @code{struct s @{ union @{ double
  12588. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  12589. inside it somewhere.
  12590.  
  12591. @item
  12592. A character type.                                                            
  12593. @end itemize
  12594.  
  12595. What do these rules say about the example in this subsection?
  12596.  
  12597. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  12598. @code{int}.  The type @code{float} is not allowed as an aliasing type
  12599. by those rules, so @code{b->size} is not supposed to alias with
  12600. elements of @code{j}.  Based on that assumption, GNU C makes a
  12601. permitted optimization that was not, in this case, consistent with
  12602. what the programmer intended the program to do.
  12603.  
  12604. Whether GCC actually performs type-based aliasing analysis depends on
  12605. the details of the code.  GCC has other ways to determine (in some cases)
  12606. whether objects alias, and if it gets a reliable answer that way, it won't
  12607. fall back on type-based heuristics.
  12608.  
  12609. @c @opindex -fno-strict-aliasing
  12610. The importance of knowing the type-based aliasing rules is not so as
  12611. to ensure that the optimization is done where it would be safe, but so
  12612. as to ensure it is @emph{not} done in a way that would break the
  12613. program.  You can turn off type-based aliasing analysis by giving GCC
  12614. the option @option{-fno-strict-aliasing}.
  12615.  
  12616. @node Digraphs
  12617. @appendix Digraphs
  12618. @cindex digraphs
  12619.  
  12620. C accepts aliases for certain characters.  Apparently in the 1990s
  12621. some computer systems had trouble inputting these characters, or
  12622. trouble displaying them.  These digraphs almost never appear in C
  12623. programs nowadays, but we mention them for completeness.
  12624.  
  12625. @table @samp
  12626. @item <:
  12627. An alias for @samp{[}.
  12628. @item :>
  12629. An alias for @samp{]}.
  12630. @item <%
  12631. An alias for @samp{@{}.
  12632. @item %>
  12633. An alias for @samp{@}}.
  12634. @item %:
  12635. An alias for @samp{#},
  12636. used for preprocessing directives (@pxref{Directives}) and
  12637. macros (@pxref{Macros}).
  12638. @end table
  12639.  
  12640. @node Attributes
  12641. @appendix Attributes in Declarations
  12642. @cindex attributes
  12643. @findex __attribute__
  12644.  
  12645. You can specify certain additional requirements in a declaration, to
  12646. get fine-grained control over code generation, and helpful
  12647. informational messages during compilation.  We use a few attributes in
  12648. code examples throughout this manual, including
  12649.  
  12650. @table @code
  12651. @item aligned
  12652. The @code{aligned} attribute specifies a minimum alignment for a
  12653. variable or structure field, measured in bytes:
  12654.  
  12655. @example
  12656. int foo __attribute__ ((aligned (8))) = 0;
  12657. @end example
  12658.  
  12659. @noindent
  12660. This directs GNU C to allocate @code{foo} at an address that is a
  12661. multiple of 8 bytes.  However, you can't force an alignment bigger
  12662. than the computer's maximum meaningful alignment.
  12663.  
  12664. @item packed
  12665. The @code{packed} attribute specifies to compact the fields of a
  12666. structure by not leaving gaps between fields.  For example,
  12667.  
  12668. @example
  12669. struct __attribute__ ((packed)) bar
  12670. @{
  12671.  char a;
  12672.  int b;
  12673. @};
  12674. @end example
  12675.  
  12676. @noindent
  12677. allocates the integer field @code{b} at byte 1 in the structure,
  12678. immediately after the character field @code{a}.  The packed structure
  12679. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  12680. alignment is 1, that of @code{char}.
  12681.  
  12682. @item deprecated
  12683. Applicable to both variables and functions, the @code{deprecated}
  12684. attribute tells the compiler to issue a warning if the variable or
  12685. function is ever used in the source file.
  12686.  
  12687. @example
  12688. int old_foo __attribute__ ((deprecated));
  12689.  
  12690. int old_quux () __attribute__ ((deprecated));
  12691. @end example
  12692.  
  12693. @item __noinline__
  12694. The @code{__noinline__} attribute, in a function's declaration or
  12695. definition, specifies never to inline calls to that function.  All
  12696. calls to that function, in a compilation unit where it has this
  12697. attribute, will be compiled to invoke the separately compiled
  12698. function.  @xref{Inline Function Definitions}.
  12699.  
  12700. @item __noclone__
  12701. The @code{__noclone__} attribute, in a function's declaration or
  12702. definition, specifies never to clone that function.  Thus, there will
  12703. be only one compiled version of the function.  @xref{Label Value
  12704. Caveats}, for more information about cloning.
  12705.  
  12706. @item always_inline
  12707. The @code{always_inline} attribute, in a function's declaration or
  12708. definition, specifies to inline all calls to that function (unless
  12709. something about the function makes inlining impossible).  This applies
  12710. to all calls to that function in a compilation unit where it has this
  12711. attribute.  @xref{Inline Function Definitions}.
  12712.  
  12713. @item gnu_inline
  12714. The @code{gnu_inline} attribute, in a function's declaration or
  12715. definition, specifies to handle the @code{inline} keywprd the way GNU
  12716. C originally implemented it, many years before ISO C said anything
  12717. about inlining.  @xref{Inline Function Definitions}.
  12718. @end table
  12719.  
  12720. For full documentation of attributes, see the GCC manual.
  12721. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  12722. the GNU Compiler Collection}.
  12723.  
  12724. @node Signals
  12725. @appendix Signals
  12726. @cindex signal
  12727. @cindex handler (for signal)
  12728. @cindex @code{SIGSEGV}
  12729. @cindex @code{SIGFPE}
  12730. @cindex @code{SIGBUS}
  12731.  
  12732. Some program operations bring about an error condition called a
  12733. @dfn{signal}.  These signals terminate the program, by default.
  12734.  
  12735. There are various different kinds of signals, each with a name.  We
  12736. have seen several such error conditions through this manual:
  12737.  
  12738. @table @code
  12739. @item SIGSEGV
  12740. This signal is generated when a program tries to read or write outside
  12741. the memory that is allocated for it, or to write memory that can only
  12742. be read.  The name is an abbreviation for ``segmentation violation''.
  12743.  
  12744. @item SIGFPE
  12745. This signal indicates a fatal arithmetic error.  The name is an
  12746. abbreviation for ``floating-point exception'', but covers all types of
  12747. arithmetic errors, including division by zero and overflow.
  12748.  
  12749. @item SIGBUS
  12750. This signal is generated when an invalid pointer is dereferenced,
  12751. typically the result of dereferencing an uninintalized pointer.  It is
  12752. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  12753. invalid access to valid memory, while @code{SIGBUS} indicates an
  12754. attempt to access an invalid address.
  12755. @end table
  12756.  
  12757. These kinds of signal allow the program to specify a function as a
  12758. @dfn{signal handler}.  When a signal has a handler, it doesn't
  12759. terminate the program; instead it calls the handler.
  12760.  
  12761. There are many other kinds of signal; here we list only those that
  12762. come from run-time errors in C operations.  The rest have to do with
  12763. the functioning of the operating system.  The GNU C Library Reference
  12764. Manual gives more explanation about signals (@pxref{Program Signal
  12765. Handling, The GNU C Library, , libc, The GNU C Library Reference
  12766. Manual}).
  12767.  
  12768. @node GNU Free Documentation License
  12769. @appendix GNU Free Documentation License
  12770.  
  12771. @include fdl.texi
  12772.  
  12773. @node Symbol Index
  12774. @unnumbered Index of Symbols and Keywords
  12775.  
  12776. @printindex fn
  12777.  
  12778. @node Concept Index
  12779. @unnumbered Concept Index
  12780.  
  12781. @printindex cp
  12782.  
  12783. @bye
  12784.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement