Learning Gnu c

  • Upload
    ucitelj

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

  • 8/8/2019 Learning Gnu c

    1/68

    Learning GNU C

  • 8/8/2019 Learning Gnu c

    2/68

  • 8/8/2019 Learning Gnu c

    3/68

    Learning GNU CA C programming tutorial or users o the GNU operating system.

    Ciaran ORiordan

    http://ciaran.compsoc.com/http://ciaran.compsoc.com/
  • 8/8/2019 Learning Gnu c

    4/68

    A C programming tutorial or users o the GNU operating system.

    Copyright c 2002, 2003, 2008 Ciaran ORiordan

    Permission is granted to copy, distribute and/or modiy this document under the

    terms o the GNU Free Documentation License, Version 1.2 or any later versionpublished by the Free Sotware Foundation; with no Invariant Sections, noFront-Cover Texts, and no Back-Cover Texts. A copy o the licence is includedin the section entitled GNU Free Documentation License.

    Published by... (not published yet)

    Cover art non existant

    http://ciaran.compsoc.com/http://ciaran.compsoc.com/
  • 8/8/2019 Learning Gnu c

    5/68

    i

    Short Contents

    Preace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

    1 Introduction to C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    32 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    4 Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

    5 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

    6 Structured Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    7 Run-time Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    8 Strings and File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    9 Storage Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    10 The C Preprocessor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    3711 Variable Length Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    12 Tricks with Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    13 Taking Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . 43

    14 Using and Writing Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

    15 Writing Good Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

    16 Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

    A Who defnes Valid C? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

    B Copying This Manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

    Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    58

  • 8/8/2019 Learning Gnu c

    6/68

    ii

    Table o Contents

    Preace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Target Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Scope o this text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Why learn C? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Why Free Sotware? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Why use GNU? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

    1 Introduction to C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.1 What are Programming Languages? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 What is C? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

    C vs. Assembly language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

    1.3 Programming Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    51.4 Introducing GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5tiny.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5tiny2.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    1.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.1 titlesd. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    hello.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.2 A Line-by-Line Dissection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.3 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    hello2.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.4 cowsd

    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    9bicycles.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    2.5 Bicycle Dissection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.6 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    sizeo types.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.7 Another Example o Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    displaying variables.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.8 Quick Explanation o print. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    more print.c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.9 Simple arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

    wages.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

    2.10 Global Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    132.11 Static Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.12 Constant Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

  • 8/8/2019 Learning Gnu c

    7/68

    iii

    3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.1 What are unctions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.2 Making your own Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    three unctions.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.3 Multiple Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    3.4 Header Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    163.5 A Larger (non)Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17main.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17display.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17display.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18prices.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18prices.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    3.6 Another new Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.7 Primer Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    4 Flow Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.1 Branching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

    using i.c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    204.2 i ... else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    cows2.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.3 Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.4 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    guess my number.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.5 or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    or ten.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.6 do .. while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    guess my number.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.7 Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    4.8 The Conditional Operator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    23apples.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    4.9 break & continue. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

    5 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255.1 The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

    pointers are simple.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255.2 The Address o a Variable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265.3 Pointers as Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

    swap ints.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265.4 Pointer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    5.5 Generic Pointers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    27generic pointer.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

  • 8/8/2019 Learning Gnu c

    8/68

    iv

    6 Structured Data Types . . . . . . . . . . . . . . . . . . . . . . . 286.1 What is Structured data? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286.2 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286.3 Declaring and Accessing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    rst arrays.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    6.4 Initialising Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    28initialise array.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296.5 Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    number square.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296.6 Arrays o Characters (Text) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306.7 Dening data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306.8 Structured Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    person struct.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306.9 Unions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

    7 Run-time Memory Allocation . . . . . . . . . . . . . . . . 327.1 Why you need this . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327.2 Dynamic Memory Functions

    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    327.3 Run-time Memory Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    8 Strings and File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . 338.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    9 Storage Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349.1 What are Storage Classes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349.2 auto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349.3 static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    list squares.c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    349.4 extern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359.5 register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359.6 the restrict type qualier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359.7 typede. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    battleships.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    10 The C Preprocessor . . . . . . . . . . . . . . . . . . . . . . . . . . 3710.1 What is the C Prepressor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3710.2 What is it used or? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    box o stars.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    10.3 Some sample macros. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    3810.4 Caveats or macros. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38max macro.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38max macro problem.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

    10.5 Are macros necessary? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3910.6 Replacing Simple Macros. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3910.7 Replacing Complex Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

  • 8/8/2019 Learning Gnu c

    9/68

    v

    11 Variable Length Arguments . . . . . . . . . . . . . . . . . 4011.1 What are Variable Length Arguments? . . . . . . . . . . . . . . . . . . . . . . . 40

    12 Tricks with Functions . . . . . . . . . . . . . . . . . . . . . . . . 4112.1 What are Virtual Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    virtual unction.c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    4112.2 Nesting unctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4112.3 The Benets o Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4112.4 Declaring and Dening Nested Functions . . . . . . . . . . . . . . . . . . . . . 41

    simple nested unction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4112.5 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

    13 Taking Command Line Arguments . . . . . . . . . 4313.1 How does C handle command line arguments? . . . . . . . . . . . . . . . . 43

    list args.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4313.2 Argp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

    simple argp.c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

    4313.3 Using More o the Argp Functionality . . . . . . . . . . . . . . . . . . . . . . . . 43

    better argp.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4413.4 Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

    14 Using and Writing Libraries. . . . . . . . . . . . . . . . . 4614.1 What are Libraries? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4614.2 Using Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4614.3 Stages o Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4614.4 Writing a library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4614.5 Dynamic or Static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

    15 Writing Good Code . . . . . . . . . . . . . . . . . . . . . . . . . . 4715.1 Readability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

    16 Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4816.1 About Optimising . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4816.2 What are unction attributes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4816.3 Function Attribute Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4816.4 What are pure and const? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

    Appendix A Who defnes Valid C? . . . . . . . . . . . . 49A.0.1 K&R C

    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49

    A.0.2 ISO C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49A.0.3 C99 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49A.0.4 GNU C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49A.0.5 Choosing a Dialect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49A.0.6 Future Standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

  • 8/8/2019 Learning Gnu c

    10/68

    vi

    Appendix B Copying This Manual . . . . . . . . . . . . 51

    Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

  • 8/8/2019 Learning Gnu c

    11/68

    Preace 1

    Preace

    Target Audience

    Welcome to Learning GNU C. The aim o this book is to teach GNU users how to writesotware in C. It is written primarily as a tutorial or beginners but it should be thoroughenough to be useul as a reerence by intermediate programmers. The basics are layed downin ull in the rst ew chapters, beginners will read these chapters careully while those withprior experience can skim through them. All the inormation is there, no prior knowledge oprogramming is assumed. Because the goal o this book is to make you a sotware developer,well then move on to some very practical usages, the likes o which normally arent taughtuntil much later in other books.

    It is assumed that you have access to a computer with a GNU system installed. Userso FreeBSD, OpenBSD, or NetBSD should also nd this manual useul. Some amiliaritywith using your computer rom the command line shell would be helpul but all neccessary

    commands will be shown along side programming examples. The only piece o sotwareyou do need experience with is a text editor. Any text editor will do. GNU Emacs is anespecially good one or programmers. It has been in development or over twenty years andcontains thousands o useul eatures. GNU Nano is a simple text editor you could use, someprogrammers like to use ViM or vi (pronounced vee eye). I you already have a avourite texteditor, you can use that. There are also graphical text editors geared towards programmerssuch as Anjuta and KDevelop but most programmers preer text based editors.

    Most GNU systems use Linux as a kernel. These systems are oten known as GNU/Linuxsystems.

    Scope o this text

    The contents o this book can be divided into two topics: the core C language, and thestandard unctionality made available to the programmer. The standard unctionality Imention is provided by GNU Libc, this is a standard library o C unctionality that is parto every GNU system. Neither o these topics is o much use without the other but there isa ocus on the core language near the beginning and more discussion on Libc near the end.The ordering o topics is designed to teach C programming in an incremental ashion whereeach chapter builds on the previous one. Some aspects o the core language are only reallyo use to experienced programmers and so appear near the end.

    The C language on its own can make decisions, repeat commands, store data, andperorm mathematics. Equally importantly, it provides a method to make use o extraunctionality such as Libc.

    Libc provides unctionality such as reading and writing les, sorting and searching data,getting input rom the user, displaying data to the user, communicating across networks,creating easily translatable programs, and many other things.

    Why learn C?

    C is a standard, it is the programmers programming language. The majority o o sotwarethat makes up GNU and BSD systems and the applications that run on them, is written inC.

  • 8/8/2019 Learning Gnu c

    12/68

    Preace 2

    C was developed over thirty years ago or writing operating systems and applications.Its small, extensible design has allowed it to evolve with the computer industry. Becauseo its age and popularity, C is a very well supported language. Many tools exist to make Cprogramming easier and these tools are oten very mature and o a high standard. All thesotware we will use in this book is written in C.

    Why Free Sotware?

    Sotware is Free Sotware when the user has the reedom to: Use the sotware or anypurpose, make changes to the sotware, share the sotware with others, and distributemodied versions o the sotware. Today, copyright law allows a sotware developer torestrict what a user can do with a piece o sotware. In 1984, Richard Stallman started theFree Sotware movement to reject this behaviour.

    Free Sotware empowers its users by allowing them to help themselves and each other bymaking changes they want to the sotware or getting someone else to make these changes.Sotware that is not Free Sotware is oten called proprietary sotware. Proprietary sotwaresays that cooperating is wrong. Producers o proprietary sotware use copyright law tomake it a criminal ofense to help others by sharing sotware.

    The goal o proprietary sotware is prot maximisation or one entity. In contrast, thegoal o Free Sotware is to be as useul as possible to as many people as possible. The GNUproject was started to reject proprietary sotware, thus reeing computer users rom havingto choose between being a criminal and betraying their community.

    Finally there are the technical benets. Free Sotware is ree rom marketing plots. Itdoesnt restrict itsel to orce users to buy extra pieces o sotware. Each piece o GNU isdesigned to be as useul as possible. As a programmer you can use the same C programmingsotware that is used in major projects.

    Proprietary sotware is generally distributed in a machine readable orm only. Thismeans that the user cannot see what what a program is really doing. Free Sotware isrequired to come with source code in a human readable ormat. As a programmer you canread the source code or any piece os Free Sotware you like. I there are errors in a program,you can x them.

    The peer review, and collaboration o thousands o programmers around the world hascreated a lot o high quality Free Sotware. The GNU/Linux operating system is one o itsgreatest achievments.

    Free Sotware will change the world or the better.

    Why use GNU?

    GNU is a complete, Unix-like operating system that has been in development or justover twenty years. GNU sotware is known or its stability, standard compliance, and thereedom it gives to computer users.

  • 8/8/2019 Learning Gnu c

    13/68

    Chapter 1: Introduction to C 3

    1 Introduction to C

    1.1 What are Programming Languages?

    A programming language is a way to give a computer a sequence o instructions to dosomething. Programming languages can be sorted into three three categories: machinelanguages, Assembly languages, and High-Level languages. O these types only machinelanguages can be understood directly by a computer.

    A machine language is the set o instructions that a computers central processing unit(CPU) understands. All instructions and inormation are represented by numbers; very astor computers, very hard or human brains to read or write. To ease the task o computerprogramming, people designed easier languages called assembly languages. An assemblylanguage is one which provides textual names or the available machine language commands.This, along with the act that assembly languages allowed programmers to add spaces andtabs to their code, made assembly languages ar easier to program with. Assembly codecan then be ed to an assembler which translates it into the machine language o the targetcomputers CPU.

    The use o assembly languages spread very ast, they became known as second generationlanguages but there were still two problems with assembly languages. Firstly, each commanddoes only a very basic task such as add two numbers or load a value rom memory. Usingthese small commands was quite tedious. The second problem was much bigger. Programswritten in an assembly language are bound to a particular type o CPU. Each type o CPUhas its own machine language and, thereore, its own assembly language.

    Finally, machine independant languages were developed, known as third generation orhigh-level languages. Designed to be easy to read, these languages were made up o Englishwords, basic mathematical symbols, and a ew punctuation characters. These languages

    allow simple statements to be expressioned concisely, or example, adding two numbers andstoring the result in memory could be expressed as:

    data = 10 + 200;

    Instead o:Load R1, 10Load R2, 200Addi R1, R2Store R2, L1

    1.2 What is C?

    C is one such high-level language. A tool called a compiler is used to convert C into machine

    code. A program can be written in C and compiled or any computer, its up to the compilerto get the hardware-specic instructions right.

    To see just how readable C is compared to Assembly language, take a look at the ollowingtiny program written in each:

    C vs. Assembly language.section .rodata

    .LC0:.string "Tax Due: %d\n"

  • 8/8/2019 Learning Gnu c

    14/68

    Chapter 1: Introduction to C 4

    .text

    .align 2.globl main

    .type main,@functionmain:

    pushl %ebp

    movl %esp, %ebpsubl $24, %espandl $-16, %esp movl $0, %eaxsubl %eax, %esp movl $1000, %eax movl $400, %edx movl $0x3e6147ae, -12(%ebp)subl %edx, %eaxpushl %eaxfildl (%esp)

    leal 4(%esp), %espfmuls -12(%ebp)

    fnstcw -18(%ebp) movw -18(%ebp), %ax movb $12, %ah movw %ax, -20(%ebp)fldcw -20(%ebp)fistpl -16(%ebp)fldcw -18(%ebp)subl $8, %esppushl -16(%ebp)

    pushl $.LC0call printfaddl $16, %esp movl $1, %eaxleaveret

    .Lfe1:.size main,.Lfe1-main

    And the same program in C:

    #include

    int

    main(){

    int wages = 1000;int tax_allowance = 400;float tax_rate = 0.22;int tax_due;

    tax_due = (wages - tax_allowance) * tax_rate;

    printf("Tax Due: %d euro\n", tax_due);

    return 0;

    }

    The output o both programs is the same: Tax Due: 131 euro. The readability winner isobvious. Whats more, the Assembly code shown is written in the 80386 instruction set, it

  • 8/8/2019 Learning Gnu c

    15/68

    Chapter 1: Introduction to C 5

    will not work on machines that use a diferent instruction set. The C code can be compiledor almost any computer.

    1.3 Programming ToolsGNU comes with a compiler called GCC. Originally this stood or GNU C Compiler butsince it can now compile languages other than C its name was changed to GNU CompilerCollection. To check i you have GCC installed, type gcc version at a command line. Iyou get a message like:

    ciaran@pooh:~/book$ gcc --versionbash: gcc: command not foundciaran@pooh:~/book$

    Then you dont have GCC installed. I you do, youll see a version number and maybesome copyright and warranty inormation, like this:

    ciaran@pooh:~/book$ gcc --versiongcc (GCC) 4.2.3 (Debian 4.2.3-1)

    Copyright (C) 2007 Free Software Foundation, Inc.This is free software; see the source for copying conditions. There is NOwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.ciaran@pooh:~/book$

    The version o GCC you have installed may be diferent, anything similar, such as 2.95.2or 3.3.0, is ok. I you got an error message saying command not ound then you dont haveGCC installed. I you installed GNU rom a CD, you should nd GCC there. I you dontknow how to install applications rom a CD then get a riend or the person who installedyour GNU system to do it or you.

    1.4 Introducing GCC

    Now were going to show you a tiny bit o C code and how to compile it. The point hereis to show you how to use GCC so we wont explain the C code yet. Heres the smallest C

    program that GCC will compile. It does nothing.

    tiny.cmain(){}

    Type this piece o code into your text editor and save it to a le called tiny.c. Youcan choose any name so long as it ends with .c, this is the extension used by C programs,

    GCC checks or this extension when compiling a program. With the le saved, you can nowcompile it into an executable program by typing:

    ciaran@pooh:~/book$ gcc tiny.cciaran@pooh:~/book$

    This command should succeed with no output. I you got any error messages check thatyou typed the program in correctly. Weighing in at eight characters well assume youvegotten this much correct and move on. A le called a.out should have appeared in yourdirectory. This is the machine language program created rom the above code, i you run it

  • 8/8/2019 Learning Gnu c

    16/68

    Chapter 1: Introduction to C 6

    you will see that it really does nothing at all. The name a.out exists or historical reasons,it is short or assembler output.

    Although GCC will compile this code, it isnt strictly complete. I we enable GCCs

    warnings we will be told what is missing. You are not expected to understand the warningmessages right now, we show this only to demonstrate GCCs warnings. You enable warningsby adding the -Wall switch to your compilation command.

    ciaran@pooh:~/book$ gcc -Wall tiny.ctiny.c:2: warning: return-type defaults to inttiny.c: In function main:tiny.c:3: warning: control reaches end of non-void functionciaran@pooh:~/book$

    These warnings appear because our program is not strictly complete. To get rid o thesewarnings we must add two more lines. So heres the smallest valid C program.

    tiny2.cint

    main(){

    return 0;}

    When we compile this with the -Wall option we will get no warnings. Another option:-o lename can be used to speciy the name you want to give to your program (instead oa.out).

    ciaran@pooh:~/book$ gcc -Wall -o tiny-program tiny2.c

    ciaran@pooh:~/book$ lstiny2.c tiny-programciaran@pooh:~/book$ ./tiny-programciaran@pooh:~/book$

    The return command ends the programs execution because it tell the program toreturn to whoever called it. Functions always return with a value. Unless otherwise dened,a return value o zero means there were no errors encountered. You can check this at thecommand line with the command echo $?. I you change return 0 to return 7, andthen recompile and run the program, then an echo $? command will diplay 7. Not veryexiting, but thats proo that your rst program did something.

    1.5 Conclusion

    This concludes our introduction. Hopeully you now have a grasp o what programmingis. In the next chapter well start writing basic programs that actually do something andexplain how they do it.

    I youre interested in more background and compiler details, you might like to readthe appendixes at the end o this book. Otherwise, lets go straight to writing your rstprogram.

  • 8/8/2019 Learning Gnu c

    17/68

    Chapter 2: Getting Started 7

    2 Getting Started

    All C programs are broken down into blocks o code called unctions. Say you wantedto write a simple program to add three numbers supplied by the user; you would need aunction to get a value rom the user, a unction to perorm the math, and a unction todisplay the answer. C programs are mostly made up o two things: unctions and data.Functions are blocks o code that complete a task while data is inormation stored in theprogram. are pieces o memory that store inormation. This inormation can be changedat any time within the program hence the name variable. The purpose o programs canusually be broken down into three actions: accept some data as input, manipulate thatdata, output it. A simple example would be the command ls you type into your shell. lsis a program, written in C, that gathers directory inormation rom your operating system,converts it to a human readable ormat, and outputs it to your terminal.

    2.1 titlesd

    The rst thing we will look at is outputing data. Data is a very broad term, but in C isall comes down to numbers. Rather than get bogged down in the theory well jump into aquick program that displays a message to your screen.

    The rst piece o useul code we will look at is a classic. When compiled and run it willdisplay a simple greeting to your screen. This program defnes a unction called main() andcalls (uses) a unction called print(). print() is a unction provided or us by the StandardDevice Input/Output library. This library comes with every GNU system. Heres our littleprogram:

    hello.c#include

    intmain(){

    printf("hello, world\n");

    return 0;}

    Compile and run this program beore moving on. I all goes well, it will display the textstring hello, world to your terminal (the standard output device). Heres the compilationcommand just in case youve orgotten:

    ciaran@pooh:~/book$ gcc -Wall -o hello hello.cciaran@pooh:~/book$ ./hellohello, world

    ciaran@pooh:~/book$

    I you got any error or warning messages check that your code matches the code in thisbook exactly. Any messages you got should tell you the line o code where your mistake is.I youve typed the code in correctly you will get no such messages.

    In this example we placed the text string "hello, world" in the parenthesis ollowing theprint(). A printing unction wouldnt be much good i you couldnt tell it what to print.Many standard unctions require you to pass arguments to them that will tell them howyou want their job done.

  • 8/8/2019 Learning Gnu c

    18/68

    Chapter 2: Getting Started 8

    2.2 A Line-by-Line Dissection

    Well do a quick description o what each line does. Dont worry i your not sure aboutsome parts, well do plenty more examples.

    #include

    This line tells GCC to include inormation about how to use the unctions rom theStandard Device Input/Output library. Usually the standard input device is your keyboardand the standard output device a terminal (which is displayed on your monitor). Thislibrary is very widely used, well come across a lot o unctions rom it in this book.

    int

    main()

    These two lines begin the denition o the unction main. Well explain the rst o thesetwo lines later.

    {

    The open curly braces signals the beginning o a block o code. All code between thiscurly brace and its matching closing brace is part o the unction main.

    printf("hello, world\n");

    This line is a unction call, the unction is already dened or you.

    return 0;

    The return statement ends execution o the unction main, any statements ater this linewould not be executed. When main() ends, your program exits. When a unction ends, itcan pass a value back to whoever called it, this is done by placing the value ater return.

    main always returns an integer (a positive or negative number with no decimal point). Wetell the compiler to expect this by preceding the denition o main with int. When returningrom main() it is convention to return zero i no problems were encountered.

    }

    The closing curly brace signals the end o the block o code that makes up main.

    The two lines that make up the body o main are known as statements. More specicallythey are simple statements (as opposed to compound statements which we will encounterin chapter 4). Statements are to C what sentences are to spoken languages. A semi-colonends a simple statement. The blank lines in the program are optional, C never requires ablank line but they make code much easier to read.

    We mentioned that our unction main returns the value zero. For most unctions thereturn value can be used within the program but since returning rom main ends the pro-gram, it returns the value to the shell. Your shell stores this value, i youd like to see it

    just type:ciaran@pooh:~/book$ gcc -Wall -o hello hello.cciaran@pooh:~/book$ ./hellohello, worldciaran@pooh:~/book$ echo $?0

    ciaran@pooh:~/book$

    To veriy this you can change the value in the program rom zero to ninety-nine, recompileand re-run the program. Youll see 99 on your screen.

  • 8/8/2019 Learning Gnu c

    19/68

    Chapter 2: Getting Started 9

    2.3 Comments

    Comments are a way to add explanatory text to your program. Just like blank lines, they

    are ignored by the compiler so they dont afect your program in any way. As the programs

    you write get larger you will nd it helpul to have comments in your code to remind youwhat you were thinking. In the examples in this book we will use comments to explain what

    is going on. There are two ways to insert a comment into your program, the most common

    way is to start and end your comments with /* and */ respectively. Comments o this sort

    can span multiple lines. The second way is by placing // at the start o your comment.

    Comments o this sort are terminated at the end o a line. Heres our hello, world program

    with comments.

    hello2.c/* The purpose of this program is to

    * display some text to the screen

    * and then exit.*/

    #include

    intmain(){

    /* printf displays a string */printf("hello, world\n");

    return 0; //zero indicates there were no errors}

    When compiled, this code will produce exactly the same executable. Lines 2 and 3 othe comment at the top start with an asterisk, this is not necessary but it makes it clearthat the comment extends or our lines.

    2.4 cowsd

    variables to store data. C programs can change the data stored in a variable at any time,hence the name. Every variable has an identier which you can use to reer to its data whenyou want to use or change its value. An expression is anything that can be evaluated i.e.1 + 1 is an expression o the value 2. In this expression, the plus sign is a binary operator;it operates on two values to create a single value.

    The rules or naming a variable are the same as or naming a unction, you can use letters,

    numbers, and the underscore character and the rst character must not be a number. Also

    like unctions, variables must be declared beore they can be used. The identier you give to

    a variable should say what the the variable will be used or, this makes you code much easier

    to read. You can dene your own variables or you can use one o the types already dened

    or you. Beore we get bogged down in terminology lets look at a quick code example to

    show how simple it all is. In this example we will use two variables o the pre-dened type

    int.

  • 8/8/2019 Learning Gnu c

    20/68

    Chapter 2: Getting Started 10

    bicycles.c#include

    int

    main(){

    int number_of_bicycles;int number_of_wheels;

    number_of_bicycles = 6;number_of_wheels = number_of_bicycles * 2;

    printf("I have %d bicycles\n", number_of_bicycles);printf("So I have %d wheels\n", number_of_wheels);

    return 0;}

    2.5 Bicycle DissectionThere are a ew new things to look at here, well break the program into chunks to explainthem.

    int number_of_bicycles;int number_of_wheels;

    These two lines each declare a variable. int is one o the built-in data types o the Clanguage. Variables o type int can store positive or negative whole numbers.

    number_of_bicycles = 6;

    This line stores the value 6 in the variable number_of_bicycles. The equals sign isknown as the assignment operator, it assigns the value on the right hand side o it to the

    variable on the let hand side.number_of_wheels = number_of_bicycles * 2;

    Again, this line uses the assignment operator but it also uses the multiplication operator.The asterisk is another binary operator, it multiplies two values to create a single value. Inthis case it creates the value 12 which is then stored in number_of_wheels.

    printf("I have %d bicycles\n", number_of_bicycles);printf("So I have %d wheels\n", number_of_wheels);

    Here we see printf again but its being used unlike we have seen beore. Here it istaking two arguments which are separated by a comma. The rst argument to printf isknown as the ormat string. When a %d is encountered in the ormat string printf knows

    to expect an extra argument. The %d is replaced by the value o this extra argument. Oneaddition argument is expected or each %d encountered.

    With this new knowledge it should be no surprise that when we compile and run thispiece o code we get the ollowing:

    I have 6 bicyclesSo I have 12 wheels

    As always, dont worry i you are unsure about certain parts. Well do plenty moreexamples.

  • 8/8/2019 Learning Gnu c

    21/68

    Chapter 2: Getting Started 11

    2.6 Data Types

    All the data types dened by C are made up o units o memory called bytes. On mostcomputer architectures a byte is made up o eight bits, each bit stores a one or a zero.

    These eight bits with two states give 256 combinations (28). So an integer which takes uptwo bytes can store a number between 0 and 65535 (0 and 216. Usually however, integervariables use the rst bit to store whether the number is positive or negative so their valuewill be between -32768 and +32767.

    As we mentioned, there are eight basic data types dened in the C language. Five typesor storing integers o varying sizes and three types or storing oating point values (valueswith a decimal point). C doesnt provide a basic data type or text. Text is made up oindividual characters and characters are represented by numbers. In the last example weused one o the integer types: int. This is the most commonly used type in the C language.

    The majority o data used in computer programs is made up o the integer types, welldiscuss the oating point types a little later. In order o size, starting with the smallest, the

    integer types are char, short, int, long and long long. The smaller types have the advantageo taking up less memory, the larger types incur a perormance penalty. Variables o typeint store the largest possible integer which does not incur this perormance penalty. Forthis reason, int variables can be diferent depending what type o computer you are using.

    The char data type is usually one byte, it is so called because they are commonly usedto store single characters. The size o the other types is dependent on the hardware o yourcomputer. Most desktop machines are 32-bit, this reers to the size o data that they aredesigned or processing. On 32-bit machines the int data type takes up 4 bytes (232). Theshort is usually smaller, the long can be larger or the same size as an int and nally thelong long is or handling very large numbers.

    The type o variable you use generally doesnt have a big impact on the speed or memory

    usage o your application. Unless you have a special need you can just use int variables. Wewill try to point out the ew cases where it can be important in this book. A decade ago,most machines had 16-bit processors, this limited the size o int variables to 2 bytes. Atthe time, short variables were usually also 2 bytes and long would be 4 bytes. Nowadays,with 32-bit machines, the deault type (int) is usually large enough to satisy what used torequire a variable o type long. The long long type was introduced more recently to handlevery large numeric values.

    Some computers are better at handling really big numbers so the size o the data types

    will be bigger on these machines. To nd out the size o each data type on your machine

    compile and run this piece o code. It uses one new language construct sizeof. This tells

    you how many bytes a data type takes up.

    sizeo types.cintmain()

    {printf("sizeof(char) == %d\n", sizeof(char));printf("sizeof(short) == %d\n", sizeof(short));printf("sizeof(int) == %d\n", sizeof(int));printf("sizeof(long) == %d\n", sizeof(long));printf("sizeof(long long) == %d\n", sizeof(long long));

  • 8/8/2019 Learning Gnu c

    22/68

    Chapter 2: Getting Started 12

    return 0;}

    2.7 Another Example o AssignmentTime or another example. This bit o code demonstrates a ew more new things which

    well explain in a minute.

    displaying variables.c#include

    int main (){

    short first_number = -5;long second_number, third_number;

    second_number = 20000 + 10000;

    printf ("the value of first_number is %hd\n", first_number);printf ("the value of second_number is %ld\n", second_number);printf ("the value of third_number is %ld\n", third_number);

    return 0;}

    Weve used a short and two long variables. We could have used int variables but choseto use other types to show how similar they are. In the rst line o main we declare avariable and give it a value all in one line. This is pretty normal. The second line declarestwo variables at once by separating them with a comma. This can be handily but code is

    oten more readable when variable declarations get a line to themselves.The third line is very like some code rom the rst example, the addition operator

    produces the value 30000 which gets stored in second number. The last thing to pointout is that instead o %d, the ormat string o printf contains %hd or the short variableand %ld or the long variables. These little groupings o characters are called conversionspecifers. Each type o variable has its own conversion specier. I you want to print asingle percent sign (%) you must write %%.

    When you compile and run this you will see the value o your variables. The value othird number will be strange. This is because it was never assigned a value. When youdeclare a variable, the operating system allocates some memory or it. You have no wayo know what this memory was used or previously. Until you give your variable a value,

    the data stored in it is essentially random. Forgetting to assign a value to a variable is acommon mistake among beginning programmers.

    2.8 Quick Explanation o print

    You may have noticed two characters near the end o our printf statements \n. Thesedont get displayed to the screen, they are the notation printf uses to represent newline.\ is the c escape character when it is encountered within quotes the ollowing characterusually has a special meaning. Another example is \t which is used to represent a TAB.

  • 8/8/2019 Learning Gnu c

    23/68

    Chapter 2: Getting Started 13

    Another special character that printf looks out or is %, this tells it to look at thenext ew characters and be ready to replace them with the value o a variable. %d is thecharacter sequence that represents a variable o type int to be displayed using the decimalcounting system (0 .. 9). For every %d in the ormat string you must tell printf whatvariable you want it replaced with. Heres some more use o printf in code:

    more print.cintmain(){

    int one = 1;int two = 2;int three = 4; /* the values are unimportant here */

    printf ("one ==\t%d\ntwo ==\t%d\nthree ==\t%d\n", one, two, three);

    return 0;

    }

    2.9 Simple arithmetic

    We mentioned at the start o this chapter that point o a program usually involves perorm-ing actions on data. By using standard mathematical symbols, arithmetic in C is easilyreadable.

    wages.cintmain(){

    int hours_per_day;int days_per_week;

    hours_per_day = 8;days_per_week = 5;

    printf ("I work %d hours a week.\n", (days_per_week * hours_per_day) );

    printf ("%d %d hour days\n", days_per_week, hours_per_day);

    return 0;}

    2.10 Global VariablesThese have there place but are oten used to x badly written code. I two unctions needto operate on a variable you should use pointers to share this variable rather than make itavailable to every unction.

    2.11 Static Variables

    text.

  • 8/8/2019 Learning Gnu c

    24/68

    Chapter 2: Getting Started 14

    2.12 Constant Variables

    A good rule to ollow is to never use numbers other than 1 and 0 in your code. I yourequire another numeric constant you should make it a const variable; this way it gets a

    nice meaningul name. The number 40 has little meaning, however, the identier HOURS_WORKED_PER_WEEK tells us something about what a unction is doing. Another benet isthat you can change the value o a const variable in one place rather than having to changeall occurrences o 40. Using the latter method it is easy to make a mistake by changing anunrelated occurrence o 40 or orgetting to change an occurrence.

  • 8/8/2019 Learning Gnu c

    25/68

    Chapter 3: Variables 15

    3 Variables

    3.1 What are unctions?

    C programs are generally broken down into tasks. To calculate the bill at a resteraunt youneed some code to ask or the costs o each dish, calculate the total, and then display theanswer. Each o these tasks is taken care o by a unction.

    In the last chapter we wrote a do-nothing program, this program consisted on one unc-tion, main. When writing real sotware your programs will be made up o tens or hundredso unctions. When you write a program you will write many unctions to perorm the tasksyou need. There are, however, a lot o common tasks such as displaying text to the screenthat a lot o programmers will need. Instead o having everyone reinventing the wheel, GNUsystems come with libraries o pre-dened unctions or many o these tasks. Over the years,thousands o such unctions have accumulated. I you were writing a program that plays thegame, BINGO, you would have to write the game specic unctions yoursel but you wouldnd that others have already written unctions or generating random numbers, displayingresults to the screen, getting input rom the player etc.

    Every C program must have a unction called main, this is where execution o theprogram begins. The code o a program could be completely contained in main but it ismore usual to split a program into many small unctions.

    3.2 Making your own Functions

    In that last example we dened just one unction. To add another unction you mustgenerally do two things. First you must defne the unction, just like we dened main. Alsoyou you must declare it. Declaring a unction is like telling GCC to expect it, we didnt haveto declare main because it is a special unction and GCC knows to expect it. The name, oridentier, you give to a unction must appear in both the denition and the declaration.

    Functions identiers can be made up o the alphabetic characters a-z and A-Z, thenumeric characters 0-9 and the underscore character . These can be used in any order solong as the rst character o the identier is not a number. As we said earlier, C is case-sensitive so My_Function is completely diferent to my_function. A unctions identiermust be unique. Identiers can saely be up to 63 characters long or as short as 1 character.

    Along with its identier you must give each unction a type and a block o code. Thetype tells the compiler what sort o data it returns. The return value o a unction can beignored, printf returns an integer saying how many character it displayed to the terminal.This inormation wasnt important to us so we ignored it in our program. In the nextchapter well discuss types o data in detail, until then well gloss over return values.

    Heres a program that denes three unctions:

    three unctions.c#include

    /* function declarations */int first_function (void);int goodbye (void);

  • 8/8/2019 Learning Gnu c

    26/68

    Chapter 3: Variables 16

    int main () // function definition{

    printf ("the program begins...\n");first_function ();goodbye ();

    return 0;}

    intfirst_function () // function definition{

    /* this function does nothing */return 0;

    }

    intgoodbye () // function definition{

    printf ("...and the program ends.\n");

    return 0;}

    In the above example we wrote first_function which does nothing and goodbye whichdisplays a message. Functions must be declared beore they can be called are called, in ourcase this means they must appear our denition o main. In practice, unction declarationsare generally grouped at the top o a le ater any #include lines and beore any unctiondenitions.

    3.3 Multiple Files

    Programs do not have to be written in just one le, your code can split up into as manyles as you want, i a program is comprised o orty unctions you could put each unctioninto a separate le. This is a bit extreme though. Oten unctions are grouped by topicand put into separate les. Say you were writing a program that worked out the price oa pizza and displayed the result, you could put the calculation unctions into one le, thedisplay unctions into another and have main in a third one. The command you would useto compile your program would look something like this:

    ciaran@pooh:~/book$ gcc -o pizza_program main.c prices.c display.c

    Remember: I you dene a unction in prices.c and you want to call this unction in

    main.c you must declare the unction in main.c.

    3.4 Header Files

    Keeping track o unction declarations can get messy, or this reason Header fles are usedto house C code that you wish to appear in multiple les. You have actually alreadyused a header le. stdio.h is a header le which contains many unction declarations,it contains the unction declarations or printf and printf. Once you have placed theunction declarations you wish to share into a header le you can #include your header

  • 8/8/2019 Learning Gnu c

    27/68

    Chapter 3: Variables 17

    in each C le that needs the inormation. The only diference being that you surroundyour lename in quotes instead o angle brackets ("my_header.h" instead o ). To illustrate these points well write that pizza program I mentioned earlier.

    3.5 A Larger (non)Program

    The small amount o programming we have shown so ar isnt enough to make a decentinteractive program. To keep it simple, we will write just a skeleton program so you cansee the structure and usage o header les without getting bogged down in new concepts.In Chapter 3 we will write a ull version o this program. The code here can be compiledand run but it will not ask the user or any input or calculate the price.

    First we have main.c, this will only contain the unction main. main will call some

    o the unctions we dene in other les. Note that main.c doesnt have a line #include

    as it does not use any o the unctions in the Standard Device I/O library.

    main.c#include "display.h"#include "prices.h"

    intmain(){

    display_options ();calculate_price ();display_price ();

    return 0;}

    Next we have display.c. This contains two unctions, both o which are called rom

    main and so we put there declarations in a header le display.h.

    display.c#include

    intdisplay_options (){

    printf ("Welcome to the pizza parlor\n");printf ("What size pizza would you like? (in inches)");

    return 0;}

    int

    display_price (){

    printf ("Your pizza will cost 0.00\n");

    return 0;}

  • 8/8/2019 Learning Gnu c

    28/68

    Chapter 3: Variables 18

    display.h/* header file just contains function declarations, an file that wants

    * to use either of these functions just has to #include this file */int display_options (void);

    int display_price (void);

    Finally we have prices.c which contains the unctions or getting input rom the user

    and calculating the total cost o the pizza. Only one o these unctions is called rom main,

    the declarations or the other two are thereore put at the top o the le. Well ll in the

    code or these unctions in Chapter 3.

    prices.cint get_size (void);int get_toppings (void);

    intcalculate_price (){

    /* insert code here. Will call get_size() and get_toppings(). */return 0;

    }

    intget_size (){

    /* insert code here */return 0;

    }

    int get_toppings ()

    {/* insert code here */return 0;

    }

    prices.hint calculate_price (void);

    This can then be compiled with the command: gcc -Wall -o pizza_program main.cprices.c display.c. When run, it will display a greeting and announce that your pizzacosts E0.00.

    3.6 Another new Function

    Beore we move on, lets take a look at one more unction rom the Standard Device I/OLibrary: printf. The Print Formatted command is an advanced orm o printf. Thestring you pass to printf can contain character sequences which have special meanings.Unlike printf, there is no automatic new-line at the end o a string displayed by printfto insert a new-line you add the characters \n.

  • 8/8/2019 Learning Gnu c

    29/68

    Chapter 3: Variables 19

    3.7 Primer Summary

    What weve covered so ar shouldnt be too hard. I youd like to experiment, try writingsimilar programs that output a ew lines. Split your program into a couple o unctions and

    divide them into two les.Always enable GCCs warnings when compiling your program. Warnings mean your

    code is unclear or incomplete, GCC will guess at the correct meaning and will usually getit right but you should not rely on this. Looking at and correcting the warnings will helpyou get used to the language. Most warnings are accompanied by the line number wherethe problem is. I you cant see anything wrong with that line check the line above it;i a statement is incomplete GCC wont notice that it is an error until it encounters thebeginning o the ollowing statement. Dont orget your semi-colons.

  • 8/8/2019 Learning Gnu c

    30/68

    Chapter 4: Flow Control 20

    4 Flow Control

    Taking actions based on decisions

    C provides two sytles o decision making: branching and looping. Branching is decidingwhat actions to take and looping is deciding how many times to take a certain action.

    4.1 Branching

    Branching is so called because the program chooses to ollow one branch or another. Thei statement is the most simple o the branching statements. It takes an expression inparenthesis and an statement or block o statements (surrounded by curly braces). i theexpression is true (evaluates to non-zero) then the statement or block o statements getsexecuted. Otherwise these statements are skipped. i statements take the ollowing orm:

    if (expression)statement;

    or

    if (expression){

    statement1;

    statement2;statement3;

    }

    Heres a quick code example:

    using i.c#include

    intmain(){

    int cows = 6;

    if (cows > 1)printf("We have cows\n");

    if (cows > 10)printf("loads of them!\n");

    return 0;

    }

    When compiled and run this program will display:

    ciaran@pooh:~/book$ gcc -Wall -Werror -o cows using_if.cciaran@pooh:~/book$ ./cowsWe have cows

    ciaran@pooh:~/book$

    The second printf statement does not get executed because its expression is alse(evaluates to zero).

  • 8/8/2019 Learning Gnu c

    31/68

    Chapter 4: Flow Control 21

    4.2 i ... else

    A second orm o i statement exists which allows you to also speciy a block o code to

    execute i the test expression is alse. This is known as an i ... else statement and is ormed

    by placing the reserved word else and another block o code ater the usual i statment.You program will execute one o the two blocks o code based on the test condition ater

    the i. Heres what it looks like:

    cows2.cintmain()

    {int cows = 0;

    if (cows > 1){

    printf("We have cows\n");printf("%d cows to be precise\n", cows);

    }else

    {if (cows == 0)

    printf("We have no cows at all\n");else

    printf("We have only one cow\n");}

    if (cows > 10)printf("Maybe too many cows.\n");

    return 0;}

    You should be able to guess the output by now:

    ciaran@pooh:~/book$ ./cows2We have no cows at allciaran@pooh:~/book$

    In the last example there was an if .. else statement inside another if .. else state-ment. This is perectly legal in C and is quite common. There is another orm o branchingyou can use but its a little more complex so well leave it to to end o the chapter.

    4.3 Loops

    Loops provide a way to repeat commands and control how many times they are repeated.Say you wanted to print the alphabet to the screen, you could do this with a call to printf.This is one solution but it doesnt scale very well, what i you wanted to print all thenumbers between one and one thousand in a column? this could be handled by one bigprintf or loads oprintf calls but repetitive work should be done by the computer, leavingyou more time to work on the interesting parts o your program.

  • 8/8/2019 Learning Gnu c

    32/68

    Chapter 4: Flow Control 22

    4.4 while

    The most basic loop in C is the while loop. A while statement is like a repeating i statement.Like an I statement, i the test condition is true: the statments get executed. The diference

    is that ater the statements have been executed, the test condition is checked again. I itis still true the statements get executed again. This cycle repeats until the test conditionevaluates to alse. I the test condition is alse the rst time, the statments dont getexecuted at all. On the other hand i its test condition never evaluates to alse it maycontinue looping innitely. To control the number o times a loop executes its code youusually have at least one variable in the test condition that gets altered in the subsequentblock o code. This allows the test condition to become alse at some point.

    Heres the quick example you are probably expecting. Its a simple guessing game, very

    simple or the person who is writing the code as they know the answer. When testing this

    program remember to guess the wrong answer a ew times.

    guess my number.c#include

    intmain(){

    const int MAGIC_NUMBER = 6;int guessed_number;

    printf("Try to guess what number Im thinking of\n");printf("HINT: Its a number between 1 and 10\n");

    printf ("enter your guess: ");scanf ("%d", &guessed_number);

    while (guessed_number != MAGIC_NUMBER){

    printf ("enter your guess: ");scanf ("%d", &guessed_number);

    }

    printf ("you win.\n");

    return 0;}

    The block o code ollowing the while statement will be executed repeatedly until theplayer guesses the number six.

    4.5 orfor is similar to while, its just written diferently. or statements are oten used to proccess

    lists such a range o numbers:

    or ten.c#include

    int

  • 8/8/2019 Learning Gnu c

    33/68

    Chapter 4: Flow Control 23

    main(){

    int i;

    /* display the numbers from 0 to 9 */for (i = 0; i < 10; i++)

    printf ("%d\n", i);

    return 0;}

    4.6 do .. while

    do .. while is just like a while loop except that the test condition is checked at the end o

    the loop rather than the start. This has the efect that the content o the loop are always

    executed at least once.

    guess my number.c#include

    intmain(){

    const int MAGIC_NUMBER = 6;int guessed_number;

    printf ("Try to guess what number Im thinking of\n");printf ("HINT: Its a number between 1 and 10\n");

    do{

    printf ("enter your guess: ");scanf ("%d", &guessed_number);

    }while (guessed_number != MAGIC_NUMBER);

    printf ("you win.\n");

    return 0;}

    4.7 Switch

    The switch statement is much like a nested if .. else statement. Its mostly a matter opreerence which you use, switch statement can be slightly more ecient and easier to read.

    4.8 The Conditional Operator

    The ?: operator is just like an if .. else statement except that because it is an operatoryou can use it within expressions.

    Blah, blah, heres an example:

    apples.c#include

  • 8/8/2019 Learning Gnu c

    34/68

    Chapter 4: Flow Control 24

    intmain(){

    int apples = 6;

    printf ("I have %d apple%s\n", apples, (apples == 1) ? "" : "s");

    return 0;}

    ?: is a ternary operator in that it takes three values, this is the only ternary operatorC has.

    4.9 break & continue

    Youve seen break already, we ended each case o our switch statement with one. breakexits out o a loop.

    continue is similar to break in that it short circuits the execution o a code block butcontinue brings execution back to the start o a loop.

  • 8/8/2019 Learning Gnu c

    35/68

    Chapter 5: Pointers 25

    5 Pointers

    sorting the programmers rom the students

    5.1 The Basics

    A limitation you may have noticed is that unctions can only afect your program via theirreturn value, so what do you do when you want a unction to alter more than one variable?You use pointers. A pointer is a special kind o variable. Pointers are designed or storingmemory address i.e. the address o another variable. Declaring a pointer is the same asdeclaring a normal variable except you stick an asterisk * in ront o the variables identier.There are two new operators you will need to know to work with pointers. The address ooperator & and the dereerencing operator *. Both are prex unary operators. Whenyou place an ampersand in ront o a variable you will get its address, this can be storein a pointer. When you place an asterisk in ront o a pointer you will get the value atthe memory address pointed to. As usual, well look at a quick code example to show howsimple this is.

    pointers are simple.c#include

    intmain(){

    int my_variable = 6, other_variable = 10;int *my_pointer;

    printf ("the address of my_variable is : %p\n", &my_variable);printf ("the address of other_variable is : %p\n", &other_variable);

    my_pointer = &my_variable;

    printf ("\nafter \"my_pointer = &my_variable\":\n");printf ("\tthe value of my_pointer is %p\n", my_pointer);printf ("\tthe value at that address is %d\n", *my_pointer);

    my_pointer = &other_variable;

    printf ("\nafter \"my_pointer = &other_variable\":\n");printf ("\tthe value of my_pointer is %p\n", my_pointer);printf ("\tthe value at that address is %d\n", *my_pointer);

    return 0;}

    The output shows you the address o the two variables, the addresses your system assignsto the variables will be diferent to mine. In printf youll notice we used %p to display theaddresses. This is the conversion specier or all pointers. Anyway, heres the output I got:

    the address of my_variable is : 0xbffffa18the address of other_variable is : 0xbffffa14

    after "my_pointer = &my_variable":the value of my_pointer is 0xbffffa18the value at that address is 6

  • 8/8/2019 Learning Gnu c

    36/68

    Chapter 5: Pointers 26

    after "my_pointer = &other_variable":the value of my_pointer is 0xbffffa14the value at that address is 10

    There. Thats not too complicated. Once you are comortable with pointers youre wellon your way to mastering C.

    5.2 The Address o a Variable

    When your program is running and a variable declaration is encountered, you programmakes a request or some memory. The operating system nds a spare piece o memorythat is large enough and tells your program the address o this piece o memory. Any timeyour program wants to read the data stored in that variable, it looks at its memory addressand reads the number o bytes equal to the size o the data type o that variable.

    I you run the example rom the start o this chapter a second time you may or maynot get the same result or the addresses, this depends on your system but even i you

    repeatably get the same addresses right now there is no guarantee that you will get thesame result tomorrow, in act its rather unlikely.

    5.3 Pointers as Function Arguments

    One o the best things about pointers is that they allow unctions to alter variables outsideo there own scope. By passing a pointer to a unction you can allow that unction to readand write to the data stored in that variable. Say you want to write a unction that swapsthe values o two variables. Without pointers this would be practically impossible, hereshow you do it with pointers:

    swap ints.c

    #include

    int swap_ints (int *first_number, int *second_number);

    intmain(){

    int a = 4, b = 7;

    printf ("pre-swap values are: a == %d, b == %d\n", a, b);

    swap_ints (&a, &b);

    printf ("post-swap values are: a == %d, b == %d\n", a, b)

    return 0;}

    int

    swap_ints (int *first_number, int *second_number){

    int temp;

    /* temp = "what is pointed to by" first_number; etc... */temp = *first_number;

  • 8/8/2019 Learning Gnu c

    37/68

    Chapter 5: Pointers 27

    *first_number = *second_number;*second_number = temp;

    return 0;}

    As you can see, the unction declaration oswap_ints tells GCC to expect two pointers(address o variables). Also, the address-o operator (&) is used to pass the address o thetwo variables rather than their values. swap_ints then reads

    5.4 Pointer Arithmetic

    Arithmetic can be perormed on pointers just like any other variable, this is only useul in aew cases though. I you were (or some reason) to divide a pointer by two it would then pointto an area o your computers memory that would probably not belong to your program. Iyour program tried to read or write to this area o memory the text segmentation ault willdisplay and your program will abort. A segmentation ault occurs when a program tries to

    access a segment o memory that it does not have permission to access.There are times however when simple addition can be used on a pointer. Well see

    this in the next chapter when we discuss arrays (multiple variables at consecutive memoryaddresses). In the case o addition (and subtraction), arithmetic is perormed in units equalto the size o the pointers data type.

    5.5 Generic Pointers

    When a variable is declared as being a pointer to type void it is known as a generic pointer.Since you cannot have a variable o type void, the pointer will not point to any data andthereore cannot be dereerenced. It is still a pointer though, to use it you just have to castit to another kind o pointer rst. Hence the term Generic pointer.

    This is very useul when you want a pointer to point to data o diferent types at diferenttimes.

    Here is some code using a void pointer:

    generic pointer.cintmain(){

    int i;char c;void *the_data;

    i = 6 ;

    c = a;

    the_data = &i;printf ("the_data points to the integer value %d\n", *(int*) the_data);

    the_data = &c;

    printf ("the_data now points to the character %c\n", *(char*) the_data);

    return 0;}

  • 8/8/2019 Learning Gnu c

    38/68

    Chapter 6: Structured Data Types 28

    6 Structured Data Types

    contiguous and structured data

    6.1 What is Structured data?C provides two methods or dening structured, or aggregate data types: arrays and structs.Both can contain any o the standard data types including pointers as other structs andarrays. Arrays contain many variables o the same type while structs can contain anymixture o types.

    6.2 Arrays

    An array is a data type which contains many variables o the same type. Each element othe array is given a number by which you can access that element. For an array o 100elements, the rst element is 0 (zero) and the last is 99. This indexed access makes it very

    convenient to loop through each element o the array.

    6.3 Declaring and Accessing Arrays

    Declaring an array is much the same as declaring any other variable except that you mustspeciy the array size. The size (or number o elements) is an integer value placed in squarebrackets ater the arrays identier.

    frst arrays.cint main (){

    int person[10];float hourly_wage[4] = {2, 4.9, 10, 123.456};int index;

    index = 4;person[index] = 56;

    printf ("the %dth person is number %d and earns $%f an hour\n",(index + 1), person[index], hourly_wage[index]);

    return 0;}

    NOTE: it is up to you to make sure you dont try to access an element that is not inthe array such as the eleventh element o a ten element array. Attempting to access a valuepast the end o an array will either crash your program or worse, it could retrieve garbage

    data without telling you that an error occurred.

    6.4 Initialising Arrays

    In the above example we initialised the array hourly wage by placing a comma separatedlist o values in curly braces. Using this method you can initialise as ew or as many arrayelements as you like however you cannot initialise an element without initialising all theprevious elements. I you initialise some but not all elements o an array the remainingelements will be automatically initialised to zero.

  • 8/8/2019 Learning Gnu c

    39/68

    Chapter 6: Structured Data Types 29

    To get around this inconvenience, a GNU extension to the C language allows you toinitialise array elements selectively by number. When initialised by number, the elementscan be placed in any order withing the curly braces preceded by [index]=value. Like so:

    initialise array.c#include

    int

    main(){

    int i;int first_array[100] = { [90]=4, [0]=5, [98]=6 };double second_array[5] = { [3] = 1.01, [4] = 1.02 };

    printf ("sure enough, first_array[90] == %d\n\n", first_array[90]);printf ("sure enough, first_array[99] == %d\n\n", first_array[99]);

    for (i = 0; i < 5; i++)

    printf ("value of second_array[%d] is %f\n", i, second_array[i]);

    return 0;}

    6.5 Multidimensional Arrays

    The array we used in the last example was a one dimensional array. Arrays can have more

    than one dimension, these arrays-o-arrays are called multidimensional arrays. They are

    very similar to standard arrays with the exception that they have multiple sets o square

    brackets ater the array identier. A two dimensional array can be though o as a grid o

    rows and columns.

    number square.c#include

    const int num_rows = 7;const int num_columns = 5;

    intmain(){

    int box[num_rows][num_columns];int row, column;

    for (row = 0; row < num_rows; row++)for (column = 0; column < num_columns; column++)

    box[row][column] = column + (row * num_columns);

    for (row = 0; row < num_rows; row++){

    for(column = 0; column < num_columns; column++){

    printf("%4d", box[row][column]);}

  • 8/8/2019 Learning Gnu c

    40/68

    Chapter 6: Structured Data Types 30

    printf("\n");}

    return 0;}

    I you compile and run this example youll get a box o numbers like this:0 1 2 3 45 6 7 8 9

    10 11 12 13 1415 16 17 18 1920 21 22 23 2425 26 27 28 2930 31 32 33 34

    The above array has two dimensions and can be called a doubly subscripted array. GCCallows arrays o up to 29 dimensions although actually using an array o more than threedimensions is very rare.

    6.6 Arrays o Characters (Text)Text in C is represented by a number o consecutive variables o type char terminated withthe null character \0.

    6.7 Defning data types

    The C language provides only the most basic, commonly used types, many languages providea larger set o types but this is only or convenience. Cs way o handling text strings is agood example o this. At times you may think it would be handy i there were other datatypes which could store complex data. C allows you to dene your own.

    6.8 Structured Data

    In C you can create a new type e.g. Person. Person can store an int called age, a stringcalled name and another int called height_in_cm. Heres the code to make this new type:

    struct Person{

    char[40] name;int age;int height_in_cm;

    };

    This code creates a variable called struct Person. You can declare variable and pointers

    to variables o this type in the usual way. Say you declared a variable john o type struct

    Person. To access the age eld you would use john.age. Ill make this clearer with a quick

    example using the previous denition o struct Person:

    person struct.cint

    main(){

    struct Person hero = { 20, "Robin Hood", 191 };struct Person sidekick;

    john.age = 31;

  • 8/8/2019 Learning Gnu c

    41/68

    Chapter 6: Structured Data Types 31

    john.name = "John Little"john.height_in_cm = 237;

    printf ("%s is %d years old and stands %dcm tall in his socks\n",sidekick.name, sidekick.age, sidekick.height_in_cm);

    printf ("He is often seen with %s.\n", hero.name);

    return 0;}

    When compiled and executed this will display:John Little is 31 years old and stands 237cm tall in his socksHe is often seen with Robin Hood.

    6.9 Unions

    C also supports types that can have dynamic types, a variable that can be and int at onepoint, a double later and an unsigned long long ater that. These data types are declaredjust like a struct except they use the union keyword. Their behavior is completely diferentto a struct.

  • 8/8/2019 Learning Gnu c

    42/68

    Chapter 7: Run-time Memory Allocation 32

    7 Run-time Memory Allocation

    Requesting memory at run-time

    7.1 Why you need this

    Oten when you write a program you dont actually know how much data is will have tostore or process. In previous examples weve read in some text rom the user. Weve usedlarge character arrays to store this data but what happens i the user enters more text thanwe can handle? your program crashes. Disaster. At run-time an application can make arequest or more memory.

    7.2 Dynamic Memory Functions

    Glibc provides unctions or requesting extra memory, malloc is the st one we will showyou. You must have a pointer to start with.

    7.3 Run-time Memory Summary

    Forgetting to free memory when your nished with it is one o the worst programmingmistakes you can make. Is losing pointers a common problem? pointer alls out o scope?

  • 8/8/2019 Learning Gnu c

    43/68

    Chapter 8: Strings and File I/O 33

    8 Strings and File I/O

    Reading and writing to fles

    8.1 Introduction

    Place Holder

  • 8/8/2019 Learning Gnu c

    44/68

    Chapter 9: Storage Classes 34

    9 Storage Classes

    Changing the behavior o variables

    9.1 What are Storage Classes?

    You will have noticed that variables in unctions lose their values every time the unctionexists, this is done or reasons o eciency, the operating system doesnt know i you willneed the data again so it releases the memory allocated to your program back to the system.

    9.2 auto

    By deault, variables in C use the auto storage class. This is so called because the variablesare automatically created when needed and deleted when they all out o scope.

    You can speciy a variable to have the auto storage class by prexing the variables

    declaration with the auto keyword but this has no efect, the keyword was introduced intothe language or symmetry with the other storage speciers.

    9.3 static

    static variables are variables that dont get deleted when they all out o scope, they arepermanent and retain their value between calls to the unction. Heres an example:

    list squares.c#include

    int get_next_square(void);

    intmain(){

    int i;

    for (i = 0; i < 10; i++)printf ("%6d\n", get_next_square ());

    printf ("and %6d\n", get_next_square ());

    return 0;}

    int

    get_next_square (){static int count = 1;

    count += 1;

    return count * count;}

    This will list the squares o the numbers rom zero to ten. Zero to nine are printed bythe loop and the square o ten is printed aterwards just to show it still has its value.

  • 8/8/2019 Learning Gnu c

    45/68

    Chapter 9: Storage Classes 35

    9.4 extern

    When you declare a variable as extern your program doesnt actually reserve any memoryor it, extern means that the variable already exits external to the unction or le.

    I you want to make a variable available to every le in a project you declare it globallyin one le, that is, not inside a unction, and add an extern declaration o that variable toa header le that is included in all the other les.

    9.5 register

    The register storage class is used as a hint to the compiler that a variable is heavily used andaccess to it should be optimised i possible. Variables are usually stored in normal memory(RAM) and passed back and orth to the computers processor as needed, the speed the datais sent at is pretty ast but can be improved on. Almost all computer processors containcpu registers, these are memory slots on the actual processor, storing data there gets rido the overhead o retrieving the data rom normal memory. This memory is quite small

    compared to normal memory though so only a ew variables can be stored there. GCC willalways make use o registers by deciding what variables it thinks will be accessed oten,this works well but will never be perect because GCC doesnt know the purpose o yourprogram. By using the register keyword you can tell GCC what needs to be optimised.

    One problem with placing a variable into a cpu register is that you cant get a pointer toit, pointers can only point to normal memory. Because o this restriction GCC will ignorethe register keyword on variables whos address is taken at any point in the program.

    The resulting program will contain a request, on creation o the variable that it be placedin a cpu register, the operating system may ignore or honour this request.

    9.6 the restrict type qualifer

    This is something to do with pointers, I think it tells the compiler that a specic pointeris the only pointer to a section o memory, the compiler can optimise code better with thisknowledge. I think.

    9.7 typede

    typedef isnt much like the others, its used to give a variable type a new name. There aretwo main reasons or doing this. The most common is to give a name to a struct you havedened so that you can use your new data type without having to always precede it withthe struct keyword.

    The second use or typede is or compatibility. Say you want to store a 32-bit number.

    I you use int you are not guaranteed that it will be 32-bit on every machine. To get aroundthis you can use preprocessor directives to selectively typede a new type to the right size.

    battleships.c#include

    /* type, position coordinates and armament */struct _ship{

    int type;

  • 8/8/2019 Learning Gnu c

    46/68

    Chapter 9: Storage Classes 36

    int x;int y;int missiles;

    };

    typedef struct _ship ship;

    int main (){

    ship battle_ship_1;ship battle_ship_2 = {1, 60, 66, 8};

    battle_ship_1.type = 63;battle_ship_1.x = 54;battle_ship_1.y = 98;battle_ship_1.missiles = 12;

    /* More code to actually use this data would go here */

    return 0;}

  • 8/8/2019 Learning Gnu c

    47/68

    Chapter 10: The C Preprocessor 37

    10 The C Preprocessor

    When & how to use them

    10.1 What is the C Prepressor

    The C Preprocessor is a simple macro-expander that is run on source code les beorepassing them to the compiler. Lines that begin with the hash symbol # are directives tothe C preprocessor.

    When you create a macro you assign a name to a C expression. You can then use thisname in your code just as you would have used the expression. The preprocessor replacesall occurences o that name with the expression.

    10.2 What is it used or?

    Macros are snippets o code that get processed beore compilation. This is done by the Cpreprocessor, #define statements are macros. Take a look at this piece o code:

    box o stars.c#define SIZE_OF_SQUARE 4

    int main (){

    int i, j;

    for (i = 0; i < SIZE_OF_SQUARE; i++){

    for (j = 0; j < SIZE_OF_SQUARE; j++){printf ("*"); // print an asterisk for each column

    }

    printf ("\n"); // and a newline at the end of each row}

    }

    The output o this code will be a box:

    ****************

    The C preprocessor simply replaces the macro SIZE_OF_BOX with the value 4. Thisvery useul or two reasons:

    rstly the size o the box can be changed by just editing one line. This isnt a hugeadvantage in the above example as there are just two uses oSIZE_OF_BOX but in largerprograms this make lie much easier and removes the possibility o orgetting to changeone o the values.

    Secondly it makes the code more readable, meaningul names can be given to valuessuch as #define PI 3.142857143.

  • 8/8/2019 Learning Gnu c

    48/68

    Chapter 10: The C Preprocessor 38

    10.3 Some sample macros

    Some o the small unction in glibc are implemented as macros, getc is one

    10.4 Caveats or macrosMacros can be miss-used and its hard to catch the bugs because the macro no longer existswhen the code gets to the compiler. The most error is the macro argument with side efect.Take the this small example:

    max macro.c#define MAX (a, b) (a > b ? a : b)

    intmain(){

    int cows = 10, sheep = 12;

    printf ("we have %d of our most common animal\n", MAX (cows, sheep));

    return 0;

    }

    We compile and execute this code and get:ciaran@pooh:~/book$ ./a.outwe have 12 of our most common animal

    ciaran@pooh:~/book$

    Yup, everything looks good. Try this next example:

    max macro problem.c#define MAX (a, b) (a > b ? a : b)

    int main (){

    int cows = 10, sheep = 12;

    printf ("We have %d of our most