\input texinfo @c Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc. (The work of Trevis Rothwell and Nelson Beebe has been assigned or licensed to the FSF.) @c move alignment later? @setfilename ./c @settitle GNU C Language Manual @documentencoding UTF-8 @smallbook @synindex vr fn @copying Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc. (The work of Trevis Rothwell and Nelson Beebe has been assigned or licensed to the FSF.) @quotation Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``GNU General Public License,'' with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled ``GNU Free Documentation License.'' (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and modify this GNU manual. Buying copies from the FSF supports it in developing GNU and promoting software freedom.'' @end quotation @end copying @dircategory Programming @direntry * C: (c). GNU C Language Intro and Reference Manual @end direntry @documentencoding UTF-8 @titlepage @sp 6 @center @titlefont{GNU C} @center @titlefont{Language Intro} @center @titlefont{and} @center @titlefont{Reference Manual} @sp 4 @c @center @value{EDITION} Edition @sp 5 @center Richard Stallman @center and @center Trevis Rothwell @center plus Nelson Beebe @center on floating point @page @vskip 0pt plus 1filll @insertcopying @sp 2 WILL BE Published by the Free Software Foundation @* 51 Franklin Street, Fifth Floor @* Boston, MA 02110-1301 USA @* ISBN ?-??????-??-? @ignore @sp 1 Cover art by J. Random Artist @end ignore @end titlepage @summarycontents @contents @node Top @ifnottex @top GNU C Manual @end ifnottex @iftex @top Preface @end iftex This manual explains the C language for use with the GNU Compiler Collection (GCC) on the GNU/Linux system and other systems. We refer to this dialect as GNU C. If you already know C, you can use this as a reference manual. If you understand basic concepts of programming but know nothing about C, you can read this manual sequentially from the beginning to learn the C language. If you are a beginner to programming, we recommend you first learn a language with automatic garbage collection and no explicit pointers, rather than starting with C@. Good choices include Lisp, Scheme, Python and Java. C's explicit pointers mean that programmers must be careful to avoid certain kinds of errors. C is a venerable language; it was first used in 1973. The GNU C Compiler, which was subsequently extended into the GNU Compiler Collection, was first released in 1987. Other important languages were designed based on C: once you know C, it gives you a useful base for learning C@t{++}, C#, Java, Scala, D, Go, and more. The special advantage of C is that it is fairly simple while allowing close access to the computer's hardware, which previously required writing in assembler language to describe the individual machine instructions. Some have called C a ``high-level assembler language'' because of its explicit pointers and lack of automatic management of storage. As one wag put it, ``C combines the power of assembler language with the convenience of assembler language.'' However, C is far more portable, and much easier to read and write, than assembler language. This manual focuses on the GNU C language supported by the GNU Compiler Collection, version ???. When a construct may be absent or work differently in other C compilers, we say so. When it is not part of ISO standard C, we say it is a ``GNU C extension,'' because it is useful to know that; however, other dialects and standards are not the focus of this manual. We keep those notes short, unless it is vital to say more. For the same reason, we hardly mention C@t{++} or other languages that the GNU Compiler Collection supports. Some aspects of the meaning of C programs depend on the target platform: which computer, and which operating system, the compiled code will run on. Where this is the case, we say so. The C language provides no built-in facilities for performing such common operations as input/output, memory management, string manipulation, and the like. Instead, these facilities are defined in a standard library, which is automatically available in every C program. @xref{Top, The GNU C Library, , libc, The GNU C Library Reference Manual}. This manual incorporates the former GNU C Preprocessor Manual, which was among the earliest GNU Manuals. It also uses some text from the earlier GNU C Manual that was written by Trevis Rothwell and James Youngman. GNU C has many obscure features, each one either for historical compatibility or meant for very special situations. We have left them to a companion manual, the GNU C Obscurities Manual, which will be published digitally later. @menu * The First Example:: Getting started with basic C code. * Complete Program:: A whole example program that can be compiled and run. * Storage:: Basic layout of storage; bytes. * Beyond Integers:: Exploring different numeric types. * Lexical Syntax:: The various lexical components of C programs. * Arithmetic:: Numeric computations. * Assignment Expressions:: Storing values in variables. * Execution Control Expressions:: Expressions combining values in various ways. * Binary Operator Grammar:: An overview of operator precedence. * Order of Execution:: The order of program execution. * Primitive Types:: More details about primitive data types. * Constants:: Explicit constant values: details and examples. * Type Size:: The memory space occupied by a type. * Pointers:: Creating and manipulating memory pointers. * Structures:: Compound data types built by grouping other types. * Arrays:: Creating and manipulating arrays. * Enumeration Types:: Sets of integers with named values. * Defining Typedef Names:: Using @code{typedef} to define type names. * Statements:: Controling program flow. * Variables:: Details about declaring, initializing, and using variables. * Type Qualifiers:: Mark variables for certain intended uses. * Functions:: Declaring, defining, and calling functions. * Compatible Types:: How to tell if two types are compatible with each other. * Type Conversions:: Converting between types. * Scope:: Different categories of identifier scope. * Preprocessing:: Using the GNU C preprocessor. * Integers in Depth:: How integer numbers are represented. * Floating Point in Depth:: How floating-point numbers are represented. * Compilation:: How to compile multi-file programs. * Directing Compilation:: Operations that affect compilation but don't change the program. Appendices * Type Alignment:: Where in memory a type can validly start. * Aliasing:: Accessing the same data in two types. * Digraphs:: Two-character aliases for some characters. * Attributes:: Specifying additional information in a declaration. * Signals:: Fatal errors triggered in various scenarios. * GNU Free Documentation License:: The license for this manual. * Symbol Index:: Keyword and symbol index. * Concept Index:: Detailed topical index. @detailmenu --- The Detailed Node Listing --- * Recursive Fibonacci:: Writing a simple function recursively. * Stack:: Each function call uses space in the stack. * Iterative Fibonacci:: Writing the same function iteratively. * Complete Example:: Turn the simple function into a full program. * Complete Explanation:: Explanation of each part of the example. * Complete Line-by-Line:: Explaining each line of the example. * Compile Example:: Using GCC to compile the example. * Float Example:: A function that uses floating-point numbers. * Array Example:: A function that works with arrays. * Array Example Call:: How to call that function. * Array Example Variations:: Different ways to write the call example. Lexical Syntax * English:: Write programs in English! * Characters:: The characters allowed in C programs. * Whitespace:: The particulars of whitespace characters. * Comments:: How to include comments in C code. * Identifiers:: How to form identifiers (names). * Operators/Punctuation:: Characters used as operators or punctuation. * Line Continuation:: Splitting one line into multiple lines. * Digraphs:: Two-character substitutes for some characters. Arithmetic * Basic Arithmetic:: Addition, subtraction, multiplication, and division. * Integer Arithmetic:: How C performs arithmetic with integer values. * Integer Overflow:: When an integer value exceeds the range of its type. * Mixed Mode:: Calculating with both integer values and floating-point values. * Division and Remainder:: How integer division works. * Numeric Comparisons:: Comparing numeric values for equality or order. * Shift Operations:: Shift integer bits left or right. * Bitwise Operations:: Bitwise conjunction, disjunction, negation. Assignment Expressions * Simple Assignment:: The basics of storing a value. * Lvalues:: Expressions into which a value can be stored. * Modifying Assignment:: Shorthand for changing an lvalue's contents. * Increment/Decrement:: Shorthand for incrementing and decrementing an lvalue's contents. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing. * Assignment in Subexpressions:: How to avoid ambiguity. * Write Assignments Separately:: Write assignments as separate statements. Execution Control Expressions * Logical Operators:: Logical conjunction, disjunction, negation. * Logicals and Comparison:: Logical operators with comparison operators. * Logicals and Assignments:: Assignments with logical operators. * Conditional Expression:: An if/else construct inside expressions. * Comma Operator:: Build a sequence of subexpressions. Order of Execution * Reordering of Operands:: Operations in C are not necessarily computed in the order they are written. * Associativity and Ordering:: Some associative operations are performed in a particular order; others are not. * Sequence Points:: Some guarantees about the order of operations. * Postincrement and Ordering:: Ambiguous excution order with postincrement. * Ordering of Operands:: Evaluation order of operands and function arguments. * Optimization and Ordering:: Compiler optimizations can reorder operations only if it has no impact on program results. Primitive Data Types * Integer Types:: Description of integer types. * Floating-Point Data Types:: Description of floating-point types. * Complex Data Types:: Description of complex number types. * The Void Type:: A type indicating no value at all. * Other Data Types:: A brief summary of other types. Constants * Integer Constants:: Literal integer values. * Integer Const Type:: Types of literal integer values. * Floating Constants:: Literal floating-point values. * Imaginary Constants:: Literal imaginary number values. * Invalid Numbers:: Avoiding preprocessing number misconceptions. * Character Constants:: Literal character values. * Unicode Character Codes:: Unicode characters represented in either UTF-16 or UTF-32. * Wide Character Constants:: Literal characters values larger than 8 bits. * String Constants:: Literal string values. * UTF-8 String Constants:: Literal UTF-8 string values. * Wide String Constants:: Literal string values made up of 16- or 32-bit characters. Pointers * Address of Data:: Using the ``address-of'' operator. * Pointer Types:: For each type, there is a pointer type. * Pointer Declarations:: Declaring variables with pointer types. * Pointer Type Designators:: Designators for pointer types. * Pointer Dereference:: Accessing what a pointer points at. * Null Pointers:: Pointers which do not point to any object. * Invalid Dereference:: Dereferencing null or invalid pointers. * Void Pointers:: Totally generic pointers, can cast to any. * Pointer Comparison:: Comparing memory address values. * Pointer Arithmetic:: Computing memory address values. * Pointers and Arrays:: Using pointer syntax instead of array syntax. * Pointer Arithmetic Low Level:: More about computing memory address values. * Pointer Increment/Decrement:: Incrementing and decrementing pointers. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for. * Pointer-Integer Conversion:: Converting pointer types to integer types. * Printing Pointers:: Using @code{printf} for a pointer's value. Structures * Referencing Fields:: Accessing field values in a structure object. * Dynamic Memory Allocation:: Allocating space for objects while the program is running. * Field Offset:: Memory layout of fields within a structure. * Structure Layout:: Planning the memory layout of fields. * Packed Structures:: Packing structure fields as close as possible. * Bit Fields:: Dividing integer fields into fields with fewer bits. * Bit Field Packing:: How bit fields pack together in integers. * const Fields:: Making structure fields immutable. * Zero Length:: Zero-length array as a variable-length object. * Flexible Array Fields:: Another approach to variable-length objects. * Overlaying Structures:: Casting one structure type over an object of another structure type. * Structure Assignment:: Assigning values to structure objects. * Unions:: Viewing the same object in different types. * Packing With Unions:: Using a union type to pack various types into the same memory space. * Cast to Union:: Casting a value one of the union's alternative types to the type of the union itself. * Structure Constructors:: Building new structure objects. * Unnamed Types as Fields:: Fields' types do not always need names. * Incomplete Types:: Types which have not been fully defined. * Intertwined Incomplete Types:: Defining mutually-recursive structue types. * Type Tags:: Scope of structure and union type tags. Arrays * Accessing Array Elements:: How to access individual elements of an array. * Declaring an Array:: How to name and reserve space for a new array. * Strings:: A string in C is a special case of array. * Incomplete Array Types:: Naming, but not allocating, a new array. * Limitations of C Arrays:: Arrays are not first-class objects. * Multidimensional Arrays:: Arrays of arrays. * Constructing Array Values:: Assigning values to an entire array at once. * Arrays of Variable Length:: Declaring arrays of non-constant size. Statements * Expression Statement:: Evaluate an expression, as a statement, usually done for a side effect. * if Statement:: Basic conditional execution. * if-else Statement:: Multiple branches for conditional execution. * Blocks:: Grouping multiple statements together. * return Statement:: Return a value from a function. * Loop Statements:: Repeatedly executing a statement or block. * switch Statement:: Multi-way conditional choices. * switch Example:: A plausible example of using @code{switch}. * Duffs Device:: A special way to use @code{switch}. * Case Ranges:: Ranges of values for @code{switch} cases. * Null Statement:: A statement that does nothing. * goto Statement:: Jump to another point in the source code, identified by a label. * Local Labels:: Labels with limited scope. * Labels as Values:: Getting the address of a label. * Statement Exprs:: A series of statements used as an expression. Variables * Variable Declarations:: Name a variable and and reserve space for it. * Initializers:: Assigning inital values to variables. * Designated Inits:: Assigning initial values to array elements at particular array indices. * Auto Type:: Obtaining the type of a variable. * Local Variables:: Variables declared in function definitions. * File-Scope Variables:: Variables declared outside of function definitions. * Static Local Variables:: Variables declared within functions, but with permanent storage allocation. * Extern Declarations:: Declaring a variable which is allocated somewhere else. * Allocating File-Scope:: When is space allocated for file-scope variables? * auto and register:: Historically used storage directions. * Omitting Types:: The bad practice of declaring variables with implicit type. Type Qualifiers * const:: Variables whose values don't change. * volatile:: Variables whose values may be accessed or changed outside of the control of this program. * restrict Pointers:: Restricted pointers for code optimization. * restrict Pointer Example:: Example of how that works. Functions * Function Definitions:: Writing the body of a function. * Function Declarations:: Declaring the interface of a function. * Function Calls:: Using functions. * Function Call Semantics:: Call-by-value argument passing. * Function Pointers:: Using references to functions. * The main Function:: Where execution of a GNU C program begins. Type Conversions * Explicit Type Conversion:: Casting a value from one type to another. * Assignment Type Conversions:: Automatic conversion by assignment operation. * Argument Promotions:: Automatic conversion of function parameters. * Operand Promotions:: Automatic conversion of arithmetic operands. * Common Type:: When operand types differ, which one is used? Scope * Scope:: Different categories of identifier scope. Preprocessing * Preproc Overview:: Introduction to the C preprocessor. * Directives:: The form of preprocessor directives. * Preprocessing Tokens:: The lexical elements of preprocessing. * Header Files:: Including one source file in another. * Macros:: Macro expansion by the preprocessor. * Conditionals:: Controling whether to compile some lines or ignore them. * Diagnostics:: Reporting warnings and errors. * Line Control:: Reporting source line numbers. * Null Directive:: A preprocessing no-op. Integers in Depth * Integer Representations:: How integer values appear in memory. * Maximum and Minimum Values:: Value ranges of integer types. Floating Point in Depth * Floating Representations:: How floating-point values appear in memory. * Floating Type Specs:: Precise details of memory representations. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros. * Exception Flags:: Handling certain conditions in floating point. * Exact Floating-Point:: Not all floating calculations lose precision. * Rounding:: When a floating result can't be represented exactly in the floating-point type in use. * Rounding Issues:: Avoid magnifying rounding errors. * Significance Loss:: Subtracting numbers that are almost equal. * Fused Multiply-Add:: Taking advantage of a special floating-point instruction for faster execution. * Error Recovery:: Determining rounding errors. * Exact Floating Constants:: Precisely specified floating-point numbers. * Handling Infinity:: When floating calculation is out of range. * Handling NaN:: What floating calculation is undefined. * Signed Zeros:: Positive zero vs. negative zero. * Scaling by the Base:: A useful exact floating-point operation. * Rounding Control:: Specifying some rounding behaviors. * Machine Epsilon:: The smallest number you can add to 1.0 and get a sum which is larger than 1.0. * Complex Arithmetic:: Details of arithmetic with complex numbers. * Round-Trip Base Conversion:: What happens between base-2 and base-10. * Further Reading:: References for floating-point numbers. Directing Compilation * Pragmas:: Controling compilation of some constructs. * Static Assertions:: Compile-time tests for conditions. @end detailmenu @end menu @node The First Example @chapter The First Example This chapter presents the source code for a very simple C program and uses it to explain a few features of the language. If you already know the basic points of C presented in this chapter, you can skim it or skip it. @menu * Recursive Fibonacci:: Writing a simple function recursively. * Stack:: Each function call uses space in the stack. * Iterative Fibonacci:: Writing the same function iteratively. @end menu @node Recursive Fibonacci @section Example: Recursive Fibonacci @cindex recursive Fibonacci function @cindex Fibonacci function, recursive To introduce the most basic features of C, let's look at code for a simple mathematical function that does calculations on integers. This function calculates the @var{n}th number in the Fibonacci series, in which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, @dots{}. @example int fib (int n) @{ if (n <= 2) /* @r{This avoids infinite recursion.} */ return 1; else return fib (n - 1) + fib (n - 2); @} @end example This very simple program illustrates several features of C: @itemize @bullet @item A function definition, whose first two lines constitute the function header. @xref{Function Definitions}. @item A function parameter @code{n}, referred to as the variable @code{n} inside the function body. @xref{Function Parameter Variables}. A function definition uses parameters to refer to the argument values provided in a call to that function. @item Arithmetic. C programs add with @samp{+} and subtract with @samp{-}. @xref{Arithmetic}. @item Numeric comparisons. The operator @samp{<=} tests for ``less than or equal.'' @xref{Numeric Comparisons}. @item Integer constants written in base 10. @xref{Integer Constants}. @item A function call. The function call @code{fib (n - 1)} calls the function @code{fib}, passing as its argument the value @code{n - 1}. @xref{Function Calls}. @item A comment, which starts with @samp{/*} and ends with @samp{*/}. The comment has no effect on the execution of the program. Its purpose is to provide explanations to people reading the source code. Including comments in the code is tremendously important---they provide background information so others can understand the code more quickly. @xref{Comments}. @item Two kinds of statements, the @code{return} statement and the @code{if}@dots{}@code{else} statement. @xref{Statements}. @item Recursion. The function @code{fib} calls itself; that is called a @dfn{recursive call}. These are valid in C, and quite common. The @code{fib} function would not be useful if it didn't return. Thus, recursive definitions, to be of any use, must avoid infinite recursion. This function definition prevents infinite recursion by specially handling the case where @code{n} is two or less. Thus the maximum depth of recursive calls is less than @code{n}. @end itemize @menu * Function Header:: The function's name and how it is called. * Function Body:: Declarations and statements that implement the function. @end menu @node Function Header @subsection Function Header @cindex function header In our example, the first two lines of the function definition are the @dfn{header}. Its purpose is to state the function's name and say how it is called: @example int fib (int n) @end example @noindent says that the function returns an integer (type @code{int}), its name is @code{fib}, and it takes one argument named @code{n} which is also an integer. (Data types will be explained later, in @ref{Primitive Types}.) @node Function Body @subsection Function Body @cindex function body @cindex recursion The rest of the function definition is called the @dfn{function body}. Like every function body, this one starts with @samp{@{}, ends with @samp{@}}, and contains zero or more @dfn{statements} and @dfn{declarations}. Statements specify actions to take, whereas declarations define names of variables, functions, and so on. Each statement and each declaration ends with a semicolon (@samp{;}). Statements and declarations often contain @dfn{expressions}; an expression is a construct whose execution produces a @dfn{value} of some data type, but may also take actions through ``side effects'' that alter subsequent execution. A statement, by contrast, does not have a value; it affects further execution of the program only through the actions it takes. This function body contains no declarations, and just one statement, but that one is a complex statement in that it contains nested statements. This function uses two kinds of statements: @table @code @item return The @code{return} statement makes the function return immediately. It looks like this: @example return @var{value}; @end example Its meaning is to compute the expression @var{value} and exit the function, making it return whatever value that expression produced. For instance, @example return 1; @end example @noindent returns the integer 1 from the function, and @example return fib (n - 1) + fib (n - 2); @end example @noindent returns a value computed by performing two function calls as specified and adding their results. @item @code{if}@dots{}@code{else} The @code{if}@dots{}@code{else} statement is a @dfn{conditional}. Each time it executes, it chooses one of its two substatements to execute and ignores the other. It looks like this: @example if (@var{condition}) @var{if-true-statement} else @var{if-false-statement} @end example Its meaning is to compute the expression @var{condition} and, if it's ``true,'' execute @var{if-true-statement}. Otherwise, execute @var{if-false-statement}. @xref{if-else Statement}. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is simply an expression. It's considered ``true'' if its value is nonzero. (A comparison operation, such as @code{n <= 2}, produces the value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric Comparisons}.) Thus, @example if (n <= 2) return 1; else return fib (n - 1) + fib (n - 2); @end example @noindent first tests whether the value of @code{n} is less than or equal to 2. If so, the expression @code{n <= 2} has the value 1. So execution continues with the statement @example return 1; @end example @noindent Otherwise, execution continues with this statement: @example return fib (n - 1) + fib (n - 2); @end example Each of these statements ends the execution of the function and provides a value for it to return. @xref{return Statement}. @end table Calculating @code{fib} using ordinary integers in C works only for @var{n} < 47, because the value of @code{fib (47)} is too large to fit in type @code{int}. The addition operation that tries to add @code{fib (46)} and @code{fib (45)} cannot deliver the correct result. This occurrence is called @dfn{integer overflow}. Overflow can manifest itself in various ways, but one thing that can't possibly happen is to produce the correct value, since that can't fit in the space for the value. @xref{Integer Overflow}. @xref{Functions}, for a full explanation about functions. @node Stack @section The Stack, And Stack Overflow @cindex stack @cindex stack frame @cindex stack overflow @cindex recursion, drawbacks of @cindex stack frame Recursion has a drawback: there are limits to how many nested function calls a program can make. In C, each function call allocates a block of memory which it uses until the call returns. C allocates these blocks consecutively within a large area of memory known as the @dfn{stack}, so we refer to the blocks as @dfn{stack frames}. The size of the stack is limited; if the program tries to use too much, that causes the program to fail because the stack is full. This is called @dfn{stack overflow}. @cindex crash @cindex segmentation fault Stack overflow on GNU/Linux typically manifests itself as the @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation fault.'' By default, this signal terminates the program immediately, rather than letting the program try to recover, or reach an expected ending point. (We commonly say in this case that the program ``crashes''). @xref{Signals}. It is inconvenient to observe a crash by passing too large an argument to recursive Fibonacci, because the program would run a long time before it crashes. This algorithm is simple but ridiculously slow: in calculating @code{fib (@var{n})}, the number of (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals the final result. However, you can observe stack overflow very quickly if you use this function instead: @example int fill_stack (int n) @{ if (n <= 1) /* @r{This limits the depth of recursion.} */ return 1; else return fill_stack (n - 1); @} @end example Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization and using the default configuration, an experiment showed there is enough stack space to do 261906 nested calls to that function. One more, and the stack overflows and the program crashes. On another platform, with a different configuration, or with a different function, the limit might be bigger or smaller. @node Iterative Fibonacci @section Example: Iterative Fibonacci @cindex iterative Fibonacci function @cindex Fibonacci function, iterative Here's a much faster algorithm for computing the same Fibonacci series. It is faster for two reasons. First, it uses @dfn{iteration} (that is, repetition or looping) rather than recursion, so it doesn't take time for a large number of function calls. But mainly, it is faster because the number of repetitions is small---only @code{@var{n}}. @c If you change this, change the duplicate in node Example of for. @example int fib (int n) @{ int last = 1; /* @r{Initial value is @code{fib (1)}.} */ int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */ int i; for (i = 1; i < n; ++i) /* @r{If @code{n} is 1 or less, the loop runs zero times,} */ /* @r{since @code{i < n} is false the first time.} */ @{ /* @r{Now @code{last} is @code{fib (@code{i})}} @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */ /* @r{Compute @code{fib (@code{i} + 1)}.} */ int next = prev + last; /* @r{Shift the values down.} */ prev = last; last = next; /* @r{Now @code{last} is @code{fib (@code{i} + 1)}} @r{and @code{prev} is @code{fib (@code{i})}.} @r{But that won't stay true for long,} @r{because we are about to increment @code{i}.} */ @} return last; @} @end example This definition computes @code{fib (@var{n})} in a time proportional to @code{@var{n}}. The comments in the definition explain how it works: it advances through the series, always keeps the last two values in @code{last} and @code{prev}, and adds them to get the next value. Here are the additional C features that this definition uses: @table @asis @item Internal blocks Within a function, wherever a statement is called for, you can write a @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or more statements and declarations. (You can also use additional blocks as statements in a block.) The function body also counts as a block, which is why it can contain statements and declarations. @xref{Blocks}. @item Declarations of local variables This function body contains declarations as well as statements. There are three declarations directly in the function body, as well as a fourth declaration in an internal block. Each starts with @code{int} because it declares a variable whose type is integer. One declaration can declare several variables, but each of these declarations is simple and declares just one variable. Variables declared inside a block (either a function body or an internal block) are @dfn{local variables}. These variables exist only within that block; their names are not defined outside the block, and exiting the block deallocates their storage. This example declares four local variables: @code{last}, @code{prev}, @code{i}, and @code{next}. The most basic local variable declaration looks like this: @example @var{type} @var{variablename}; @end example For instance, @example int i; @end example @noindent declares the local variable @code{i} as an integer. @xref{Variable Declarations}. @item Initializers When you declare a variable, you can also specify its initial value, like this: @example @var{type} @var{variablename} = @var{value}; @end example For instance, @example int last = 1; @end example @noindent declares the local variable @code{last} as an integer (type @code{int}) and starts it off with the value 1. @xref{Initializers}. @item Assignment Assignment: a specific kind of expression, written with the @samp{=} operator, that stores a new value in a variable or other place. Thus, @example @var{variable} = @var{value} @end example @noindent is an expression that computes @code{@var{value}} and stores the value in @code{@var{variable}}. @xref{Assignment Expressions}. @item Expression statements An expression statement is an expression followed by a semicolon. That computes the value of the expression, then ignores the value. An expression statement is useful when the expression changes some data or has other side effects---for instance, with function calls, or with assignments as in this example. @xref{Expression Statement}. Using an expression with no side effects in an expression statement is pointless except in very special cases. For instance, the expression statement @code{x;} would examine the value of @code{x} and ignore it. That is not useful. @item Increment operator The increment operator is @samp{++}. @code{++i} is an expression that is short for @code{i = i + 1}. @xref{Increment/Decrement}. @item @code{for} statements A @code{for} statement is a clean way of executing a statement repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically, @example for (i = 1; i < n; ++i) @var{body} @end example @noindent means to start by doing @code{i = 1} (set @code{i} to one) to prepare for the loop. The loop itself consists of @itemize @bullet @item Testing @code{i < n} and exiting the loop if that's false. @item Executing @var{body}. @item Advancing the loop (executing @code{++i}, which increments @code{i}). @end itemize The net result is to execute @var{body} with 0 in @code{i}, then with 1 in @code{i}, and so on, stopping just before the repetition where @code{i} would equal @code{n}. The body of the @code{for} statement must be one and only one statement. You can't write two statements in a row there; if you try to, only the first of them will be treated as part of the loop. The way to put multiple statements in those places is to group them with a block, and that's what we do in this example. @end table @node Complete Program @chapter A Complete Program @cindex complete example program @cindex example program, complete It's all very well to write a Fibonacci function, but you cannot run it by itself. It is a useful program, but it is not a complete program. In this chapter we present a complete program that contains the @code{fib} function. This example shows how to make the program start, how to make it finish, how to do computation, and how to print a result. @menu * Complete Example:: Turn the simple function into a full program. * Complete Explanation:: Explanation of each part of the example. * Complete Line-by-Line:: Explaining each line of the example. * Compile Example:: Using GCC to compile the example. @end menu @node Complete Example @section Complete Program Example Here is the complete program that uses the simple, recursive version of the @code{fib} function (@pxref{Recursive Fibonacci}): @example #include int fib (int n) @{ if (n <= 2) /* @r{This avoids infinite recursion.} */ return 1; else return fib (n - 1) + fib (n - 2); @} int main (void) @{ printf ("Fibonacci series item %d is %d\n", 20, fib (20)); return 0; @} @end example @noindent This program prints a message that shows the value of @code{fib (20)}. Now for an explanation of what that code means. @node Complete Explanation @section Complete Program Explanation @ifnottex Here's the explanation of the code of the example in the previous section. @end ifnottex This sample program prints a message that shows the value of @code{fib (20)}, and exits with code 0 (which stands for successful execution). Every C program is started by running the function named @code{main}. Therefore, the example program defines a function named @code{main} to provide a way to start it. Whatever that function does is what the program does. @xref{The main Function}. The @code{main} function is the first one called when the program runs, but it doesn't come first in the example code. The order of the function definitions in the source code makes no difference to the program's meaning. The initial call to @code{main} always passes certain arguments, but @code{main} does not have to pay attention to them. To ignore those arguments, define @code{main} with @code{void} as the parameter list. (@code{void} as a function's parameter list normally means ``call with no arguments,'' but @code{main} is a special case.) The function @code{main} returns 0 because that is the conventional way for @code{main} to indicate successful execution. It could instead return a positive integer to indicate failure, and some utility programs have specific conventions for the meaning of certain numeric @dfn{failure codes}. @xref{Values from main}. @cindex @code{printf} The simplest way to print text in C is by calling the @code{printf} function, so here we explain what that does. @cindex standard output The first argument to @code{printf} is a @dfn{string constant} (@pxref{String Constants}) that is a template for output. The function @code{printf} copies most of that string directly as output, including the newline character at the end of the string, which is written as @samp{\n}. The output goes to the program's @dfn{standard output} destination, which in the usual case is the terminal. @samp{%} in the template introduces a code that substitutes other text into the output. Specifically, @samp{%d} means to take the next argument to @code{printf} and substitute it into the text as a decimal number. (The argument for @samp{%d} must be of type @code{int}; if it isn't, @code{printf} will malfunction.) So the output is a line that looks like this: @example Fibonacci series item 20 is 6765 @end example This program does not contain a definition for @code{printf} because it is defined by the C library, which makes it available in all C programs. However, each program does need to @dfn{declare} @code{printf} so it will be called correctly. The @code{#include} line takes care of that; it includes a @dfn{header file} called @file{stdio.h} into the program's code. That file is provided by the operating system and it contains declarations for the many standard input/output functions in the C library, one of which is @code{printf}. Don't worry about header files for now; we'll explain them later in @ref{Header Files}. The first argument of @code{printf} does not have to be a string constant; it can be any string (@pxref{Strings}). However, using a constant is the most common case. To learn more about @code{printf} and other facilities of the C library, see @ref{Top, The GNU C Library, , libc, The GNU C Library Reference Manual}. @node Complete Line-by-Line @section Complete Program, Line by Line Here's the same example, explained line by line. @strong{Beginners, do you find this helpful or not? Would you prefer a different layout for the example? Please tell rms@@gnu.org.} @example #include /* @r{Include declaration of usual} */ /* @r{I/O functions such as @code{printf}.} */ /* @r{Most programs need these.} */ int /* @r{This function returns an @code{int}.} */ fib (int n) /* @r{Its name is @code{fib};} */ /* @r{its argument is called @code{n}.} */ @{ /* @r{Start of function body.} */ /* @r{This stops the recursion from being infinite.} */ if (n <= 2) /* @r{If @code{n} is 1 or 2,} */ return 1; /* @r{make @code{fib} return 1.} */ else /* @r{otherwise, add the two previous} */ /* @r{fibonacci numbers.} */ return fib (n - 1) + fib (n - 2); @} int /* @r{This function returns an @code{int}.} */ main (void) /* @r{Start here; ignore arguments.} */ @{ /* @r{Print message with numbers in it.} */ printf ("Fibonacci series item %d is %d\n", 20, fib (20)); return 0; /* @r{Terminate program, report success.} */ @} @end example @node Compile Example @section Compiling the Example Program @cindex compiling @cindex executable file To run a C program requires converting the source code into an @dfn{executable file}. This is called @dfn{compiling} the program, and the command to do that using GNU C is @command{gcc}. This example program consists of a single source file. If we call that file @file{fib1.c}, the complete command to compile it is this: @example gcc -g -O -o fib1 fib1.c @end example @noindent Here, @option{-g} says to generate debugging information, @option{-O} says to optimize at the basic level, and @option{-o fib1} says to put the executable program in the file @file{fib1}. To run the program, use its file name as a shell command. For instance, @example ./fib1 @end example @noindent However, unless you are sure the program is correct, you should expect to need to debug it. So use this command, @example gdb fib1 @end example @noindent which starts the GDB debugger (@pxref{Sample Session, Sample Session, A Sample GDB Session, gdb, Debugging with GDB}) so you can run and debug the executable program @code{fib1}. @xref{Compilation}, for an introduction to compiling more complex programs which consist of more than one source file. @node Storage @chapter Storage and Data @cindex bytes @cindex storage organization @cindex memory organization Storage in C programs is made up of units called @dfn{bytes}. On nearly all computers, a byte consists of 8 bits, but there are a few peculiar computers (mostly ``embedded controllers'' for very small systems) where a byte is longer than that. This manual does not try to explain the peculiarity of those computers; we assume that a byte is 8 bits. Every C data type is made up of a certain number of bytes; that number is the data type's @dfn{size}. @xref{Type Size}, for details. The types @code{signed char} and @code{unsigned char} are one byte long; use those types to operate on data byte by byte. @xref{Signed and Unsigned Types}. You can refer to a series of consecutive bytes as an array of @code{char} elements; that's what an ASCII string looks like in memory. @xref{String Constants}. @node Beyond Integers @chapter Beyond Integers So far we've presented programs that operate on integers. In this chapter we'll present examples of handling non-integral numbers and arrays of numbers. @menu * Float Example:: A function that uses floating-point numbers. * Array Example:: A function that works with arrays. * Array Example Call:: How to call that function. * Array Example Variations:: Different ways to write the call example. @end menu @node Float Example @section An Example with Non-Integer Numbers @cindex floating point example Here's a function that operates on and returns @dfn{floating point} numbers that don't have to be integers. Floating point represents a number as a fraction together with a power of 2. (For more detail, @pxref{Floating-Point Data Types}.) This example calculates the average of three floating point numbers that are passed to it as arguments: @example double average_of_three (double a, double b, double c) @{ return (a + b + c) / 3; @} @end example The values of the parameter @var{a}, @var{b} and @var{c} do not have to be integers, and even when they happen to be integers, most likely their average is not an integer. @code{double} is the usual data type in C for calculations on floating-point numbers. To print a @code{double} with @code{printf}, we must use @samp{%f} instead of @samp{%d}: @example printf ("Average is %f\n", average_of_three (1.1, 9.8, 3.62)); @end example The code that calls @code{printf} must pass a @code{double} for printing with @samp{%f} and an @code{int} for printing with @samp{%d}. If the argument has the wrong type, @code{printf} will produce garbage output. Here's a complete program that computes the average of three specific numbers and prints the result: @example double average_of_three (double a, double b, double c) @{ return (a + b + c) / 3; @} int main (void) @{ printf ("Average is %f\n", average_of_three (1.1, 9.8, 3.62)); return 0; @} @end example From now on we will not present examples of calls to @code{main}. Instead we encourage you to write them for yourself when you want to test executing some code. @node Array Example @section An Example with Arrays @cindex array example A function to take the average of three numbers is very specific and limited. A more general function would take the average of any number of numbers. That requires passing the numbers in an array. An array is an object in memory that contains a series of values of the same data type. This chapter presents the basic concepts and use of arrays through an example; for the full explanation, see @ref{Arrays}. Here's a function definition to take the average of several floating-point numbers, passed as type @code{double}. The first parameter, @code{length}, specifies how many numbers are passed. The second parameter, @code{input_data}, is an array that holds those numbers. @example double avg_of_double (int length, double input_data[]) @{ double sum = 0; int i; for (i = 0; i < length; i++) sum = sum + input_data[i]; return sum / length; @} @end example This introduces the expression to refer to an element of an array: @code{input_data[i]} means the element at index @code{i} in @code{input_data}. The index of the element can be any expression with an integer value; in this case, the expression is @code{i}. @xref{Accessing Array Elements}. @cindex zero-origin indexing The lowest valid index in an array is 0, @emph{not} 1, and the highest valid index is one less than the number of elements. (This is known as @dfn{zero-origin indexing}.) This example also introduces the way to declare that a function parameter is an array. Such declarations are modeled after the syntax for an element of the array. Just as @code{double foo} declares that @code{foo} is of type @code{double}, @code{double input_data[]} declares that each element of @code{input_data} is of type @code{double}. Therefore, @code{input_data} itself has type ``array of @code{double}.'' When declaring an array parameter, it's not necessary to say how long the array is. In this case, the parameter @code{input_data} has no length information. That's why the function needs another parameter, @code{length}, for the caller to provide that information to the function @code{avg_of_double}. @node Array Example Call @section Calling the Array Example To call the function @code{avg_of_double} requires making an array and then passing it as an argument. Here is an example. @example @{ /* @r{The array of values to average.} */ double nums_to_average[5]; /* @r{The average, once we compute it.} */ double average; /* @r{Fill in elements of @code{nums_to_average}.} */ nums_to_average[0] = 58.7; nums_to_average[1] = 5.1; nums_to_average[2] = 7.7; nums_to_average[3] = 105.2; nums_to_average[4] = -3.14159; average = avg_of_double (5, nums_to_average); /* @r{@dots{}now make use of @code{average}@dots{}} */ @} @end example This shows an array subscripting expression again, this time on the left side of an assignment, storing a value into an element of an array. It also shows how to declare a local variable that is an array: @code{double nums_to_average[5];}. Since this declaration allocates the space for the array, it needs to know the array's length. You can specify the length with any expression whose value is an integer, but in this declaration the length is a constant, the integer 5. The name of the array, when used by itself as an expression, stands for the address of the array's data, and that's what gets passed to the function @code{avg_of_double} in @code{avg_of_double (5, nums_to_average)}. We can make the code easier to maintain by avoiding the need to write 5, the array length, when calling @code{avg_of_double}. That way, if we change the array to include more elements, we won't have to change that call. One way to do this is with the @code{sizeof} operator: @example average = avg_of_double ((sizeof (nums_to_average) / sizeof (nums_to_average[0])), nums_to_average); @end example This computes the number of elements in @code{nums_to_average} by dividing its total size by the size of one element. @xref{Type Size}, for more details of using @code{sizeof}. We don't show in this example what happens after storing the result of @code{avg_of_double} in the variable @code{average}. Presumably more code would follow that uses that result somehow. (Why compute the average and not use it?) But that isn't part of this topic. @node Array Example Variations @section Variations for Array Example The code to call @code{avg_of_double} has two declarations that start with the same data type: @example /* @r{The array of values to average.} */ double nums_to_average[5]; /* @r{The average, once we compute it.} */ double average; @end example In C, you can combine the two, like this: @example double nums_to_average[5], average; @end example This declares @code{nums_to_average} so each of its elements is a @code{double}, and @code{average} so that it simply is a @code{double}. However, while you @emph{can} combine them, that doesn't mean you @emph{should}. If it is useful to write comments about the variables, and usually it is, then it's clearer to keep the declarations separate so you can put a comment on each one. We set all of the elements of the array @code{nums_to_average} with assignments, but it is more convenient to use an initializer in the declaration: @example @{ /* @r{The array of values to average.} */ double nums_to_average[] = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @}; /* @r{The average, once we compute it.} */ average = avg_of_double ((sizeof (nums_to_average) / sizeof (nums_to_average[0])), nums_to_average); /* @r{@dots{}now make use of @code{average}@dots{}} */ @} @end example The array initializer is a comma-separated list of values, delimited by braces. @xref{Initializers}. Note that the declaration does not specify a size for @code{nums_to_average}, so the size is determined from the initializer. There are five values in the initializer, so @code{nums_to_average} gets length 5. If we add another element to the initializer, @code{nums_to_average} will have six elements. Because the code computes the number of elements from the size of the array, using @code{sizeof}, the program will operate on all the elements in the initializer, regardless of how many those are. @node Lexical Syntax @chapter Lexical Syntax @cindex lexical syntax @cindex token To start the full description of the C language, we explain the lexical syntax and lexical units of C code. The lexical units of a programming language are known as @dfn{tokens}. This chapter covers all the tokens of C except for constants, which are covered in a later chapter (@pxref{Constants}). One vital kind of token is the @dfn{identifier} (@pxref{Identifiers}), which is used for names of any kind. @menu * English:: Write programs in English! * Characters:: The characters allowed in C programs. * Whitespace:: The particulars of whitespace characters. * Comments:: How to include comments in C code. * Identifiers:: How to form identifiers (names). * Operators/Punctuation:: Characters used as operators or punctuation. * Line Continuation:: Splitting one line into multiple lines. @end menu @node English @section Write Programs in English! In principle, you can write the function and variable names in a program, and the comments, in any human language. C allows any kinds of characters in comments, and you can put non-ASCII characters into identifiers with a special prefix. However, to enable programmers in all countries to understand and develop the program, it is best given today's circumstances to write identifiers and comments in English. English is the one language that programmers in all countries generally study. If a program's names are in English, most programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can understand them. Most programmers in those countries can speak English, or at least read it, but they do not read each other's languages at all. In India, with so many languages, two programmers may have no common language other than English. If you don't feel confident in writing English, do the best you can, and follow each English comment with a version in a language you write better; add a note asking others to translate that to English. Someone will eventually do that. The program's user interface is a different matter. We don't need to choose one language for that; it is easy to support multiple languages and let each user choose the language to use. This requires writing the program to support localization of its interface. (The @code{gettext} package exists to support this; @pxref{Message Translation, The GNU C Library, , libc, The GNU C Library Reference Manual}.) Then a community-based translation effort can provide support for all the languages users want to use. @node Characters @section Characters @cindex character set @cindex Unicode @c ??? How to express ¶? GNU C source files are usually written in the @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which was defined in the 1960s for English. However, they can also include Unicode characters represented in the @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding. This makes it possible to represent accented letters such as @samp{á}, as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew, Japanese, and Korean.@footnote{On some obscure systems, GNU C uses UTF-EBCDIC instead of UTF-8, but that is not worth describing in this manual.} In C source code, non-ASCII characters are valid in comments, in wide character constants (@pxref{Wide Character Constants}), and in string constants (@pxref{String Constants}). @c ??? valid in identifiers? Another way to specify non-ASCII characters in constants (character or string) and identifiers is with an escape sequence starting with backslash, specifying the intended Unicode character. (@xref{Unicode Character Codes}.) This specifies non-ASCII characters without putting a real non-ASCII character in the source file itself. C accepts two-character aliases called @dfn{digraphs} for certain characters. @xref{Digraphs}. @node Whitespace @section Whitespace @cindex whitespace characters in source files @cindex space character in source @cindex tab character in source @cindex formfeed in source @cindex linefeed in source @cindex newline in source @cindex carriage return in source @cindex vertical tab in source Whitespace means characters that exist in a file but appear blank in a printed listing of a file (or traditionally did appear blank, several decades ago). The C language requires whitespace in order to separate two consecutive identifiers, or to separate an identifier from a numeric constant. Other than that, and a few special situations described later, whitespace is optional; you can put it in when you wish, to make the code easier to read. Space and tab in C code are treated as whitespace characters. So are line breaks. You can represent a line break with the newline character (also called @dfn{linefeed} or LF), CR (carriage return), or the CRLF sequence (two characters: carriage return followed by a newline character). The @dfn{formfeed} character, Control-L, was traditionally used to divide a file into pages. It is still used this way in source code, and the tools that generate nice printouts of source code still start a new page after each ``formfeed'' character. Dividing code into pages separated by formfeed characters is a good way to break it up into comprehensible pieces and show other programmers where they start and end. The @dfn{vertical tab} character, Control-K, was traditionally used to make printing advance down to the next section of a page. We know of no particular reason to use it in source code, but it is still accepted as whitespace in C. Comments are also syntactically equivalent to whitespace. @ifinfo @xref{Comments}. @end ifinfo @node Comments @section Comments @cindex comments A comment encapsulates text that has no effect on the program's execution or meaning. The purpose of comments is to explain the code to people that read it. Writing good comments for your code is tremendously important---they should provide background information that helps programmers understand the reasons why the code is written the way it is. You, returning to the code six months from now, will need the help of these comments to remember why you wrote it this way. Outdated comments that become incorrect are counterproductive, so part of the software developer's responsibility is to update comments as needed to correspond with changes to the program code. C allows two kinds of comment syntax, the traditional style and the C@t{++} style. A traditional C comment starts with @samp{/*} and ends with @samp{*/}. For instance, @example /* @r{This is a comment in traditional C syntax.} */ @end example A traditional comment can contain @samp{/*}, but these delimiters do not nest as pairs. The first @samp{*/} ends the comment regardless of whether it contains @samp{/*} sequences. @example /* @r{This} /* @r{is a comment} */ But this is not! */ @end example A @dfn{line comment} starts with @samp{//} and ends at the end of the line. For instance, @example // @r{This is a comment in C@t{++} style.} @end example Line comments do nest, in effect, because @samp{//} inside a line comment is part of that comment: @example // @r{this whole line is} // @r{one comment} This is code, not comment. @end example It is safe to put line comments inside block comments, or vice versa. @example @group /* @r{traditional comment} // @r{contains line comment} @r{more traditional comment} */ text here is not a comment // @r{line comment} /* @r{contains traditional comment} */ @end group @end example But beware of commenting out one end of a traditional comment with a line comment. The delimiter @samp{/*} doesn't start a comment if it occurs inside an already-started comment. @example @group // @r{line comment} /* @r{That would ordinarily begin a block comment.} Oops! The line comment has ended; this isn't a comment any more. */ @end group @end example Comments are not recognized within string constants. @t{@w{"/* blah */"}} is the string constant @samp{@w{/* blah */}}, not an empty string. In this manual we show the text in comments in a variable-width font, for readability, but this font distinction does not exist in source files. A comment is syntactically equivalent to whitespace, so it always separates tokens. Thus, @example @group int/* @r{comment} */foo; @r{is equivalent to} int foo; @end group @end example @noindent but clean code always uses real whitespace to separate the comment visually from surrounding code. @node Identifiers @section Identifiers @cindex identifiers An @dfn{identifier} (name) in C is a sequence of lette