Also available in PDF
const
Fieldsif
Statementif-else
Statementreturn
Statementswitch
Statementswitch
goto
Statement and Labels__auto_type
extern
Declarationsauto
and register
Next: The First Example [Contents][Index]
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++, 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++ 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. See The GNU C Library in 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.
• 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 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. | |
— 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 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 switch .
| |
• Duffs Device | A special way to use switch .
| |
• Case Ranges | Ranges of values for 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. | |
Next: The First Example [Contents][Index]