0% found this document useful (0 votes)
22 views

Gnu C Programming Tutorial

gnu_c_programming_tutorial

Uploaded by

au9t5teyr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
22 views

Gnu C Programming Tutorial

gnu_c_programming_tutorial

Uploaded by

au9t5teyr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 290
Edition 4.1 The GNU C Programming Tutorial Mark Burgess Faculty of Engineering, Oslo College Ron Hale-Evans Copyright © 2002 Free Software Foundation, Inc. Permission is granted to copy, distaibute and/or modify this document under ‘the terms of the GNU Fre Documentation License, Version 1.1 or any later version published by the Free Software Foundation; there being no Invariant Section, with the Front-Cover Texts being “A GNU Manual’, and with the BadeCover Texts as in (a) below. A copy of the license is included in the section entitled “GNU Free Documentation Lions”, (a) The FSF’s BadeCover Text is: “You have fieadom to aopy and modify ‘this GNU Manu, like GNU software. Copies published by the Free Software Foundation raise fimds for GNU development.” Preface ‘This book is a tutorial for the computer programming language C. Unlike BASIC or Pascal, C was not written asa teaching aid, but as a proféssional tool. Programmers love CC! Moreover, C is a standard, widely-used language, and a single C program can often be made to nm on many different kinds of computer. As Richard M, Stallman remarks in GNU Coding Standards, “Using another language is like using a non-standard feature: it ‘will cause trouble for users.” (See http: //www.gnu.org/prep/standards_toc. html.) Skeptics have said that everything that can gp wrong in C, does, True, it can be umfor- giving, and holds some difficlties that are not obvious at first, but that is because it does not withhold its powerful capabilities from the beginner. If you have come to C sacking a powerful language for writing everyday ccmputer programs, you will not be disappointed. ‘To ert the most from this book, you should have some basic computer literacy — you should be able to run a program, edit a text: file, and so on, You should also have acess to a computer running a GNU system such as GNU/Linux. (Ror more information on GNU and the philosophy of free software, see http: //sww .gmu.org/philosophy/.) ‘The tutorial introduces basic ideas in a logical order and progresses steadily. ‘You do not need to follow the order of the chapters rigprously, but if you are a beginner to C, it is recommended that you do, Later, you can retum to this book and aopy C code fiom it; the many examples range from tiny programs that illustrate the use of one simple feature, to complete applications that fill several pages. Along the way, there are also brief discussions of the philosophy behind C. (Computer languages have been around so Jong that: some jargon has developed. You should not ignore this jargon entirely, because it i the Ianguage that programmers speak. Jargon is explained wherever necessary, but kept toa minimum, There is also a glossary at ‘the back of the book, ‘The authors of this book hope you will learn everything you neod to write simple C programs from this book, Further, it is rdleased under the GNU Fie Documentation License, so as the computers and robots in the fantasies of Douglas Adams say, “Share and Enjoy!” The first edition of this book was written én 1987, then upelated and rewritten in 1999. Tt twas originally published by Dabs Press. After it went out of print, David Atherton of Dabs «and the original author, Mark Burgess, agreed to release the manuscript. At the request of the Free Softuare Foundation, the book wns further revised by Ron Hale-Bvans in 2001 and 2002. ‘The current adition is written in Teninfo, which is a documentation system using a single source file to produce both onkine information. and printed output. You ean read this tutorial online with either the Emacs Info render, the stand-alone Info render, or a World Wide Web browser, or you can rend it as a. printed book. ‘The advantages of C 1 1 Introduction What is a highalevel language? Why is C unusual? Any sufficiently complex ob ject has Jeves of detail; the amount of detail we see depends ‘on how closely we scrutinize the object. A computer has many levels of detail. ‘The terms Jow level and high level are often wed to describe these layers of complexity jn computers. ‘The Jow level is buried in the computer's microchips and microcinonits. The {ow level is the level at which the computer seams most: primitive and mechanical, whereas the high level describes the computer in Jess detail, and makes it easier to use. ‘You can see high Jewels and low levels in the workings of a car, Tn a car; the nuts, bolts, and pistons of the low level can be grouped together conceptually to form the higher-level engine. Without knowing anything about the nuts and bolts, you can treat the engine as a black box: a simple unit that: behaves in predictable ways. At an even higher level (the one mest people use when driving), you can see a car as a group of these black boxes, including the engine, the steering, the brakes, and so on. At a high level, a computer also becomes group of black boxes. Cis a high-Jovel language. The aim of any high-level computer Janguage is to provide an easy, natural way to give a list of instructions (a computer program) to a computer. ‘The native language of the computer is a stream of numbers called machine language. As you might expect, the action resulting from a single machine language instruction & very ptimitive, and many thousmds of them can be required to do something substantial. A high-level Janguage provides a set of instructions you can recambine creatively and give to the imaginary black bawes of the computer. The high-level language software will then ‘translate these high-level instructions into lovelevel machine language instructions. 1.1 The advantages of C Cisne of a large mmber of high-level languages designed for general-purpose program ning, in other words, for writing anything from small programs for personal ammsement: to complex industrial applications, (Chas many advantages: «Before C, machine language programmers criticized high-level languages because, with ‘heir black box approach, they shielded the user from the working details of the cam- puter and all its facilities. C, however, was designed to give access to any level of the computer down to raw machine language, and becanse of this, it is perhaps the most flexible high-level language. © Chas features that allow the programmer to organize programs in a clear, easy, logical way. For example, C allows meaningful names for variables without: any loss of effi ciency, yet it gives a complete freedom of programming style, including flexible ways of making decisions, and a set of flexible commends for performing tasks repetitively (for, winile, do). © Cis sucinct, Tt permits the creation of tidy, compact programs. ‘This feature can be a mixed blessing, however, and the C progtammer mst balance simplicity and readability, 2 Chapter 1: Introduction © Callows commands that are invalid in other languages. This is no defect, but a powerfull freodom which, when used with caution, makes many things possible, Tt does mean, that there are concealed difficulties in C, but if you write carefully and thoughtfully, you can create fast, efficent programs. With G, you can use every resource your compnter offers, C tries to link closely with ‘the local environment, providing facilities for gaining access to common peripherals, like disk drives and printers. When new peripherals are invented, the GNU community quickly provides the ability to program them in C as well. In fact, most of the GNU project is written in G (as are many other operating systems). For the reasons outlined above, C is the preeminent high-level language. Clearly, no Tanguage can guarantee good programs, but C can provide a framework in which it is easy ‘to program well. 1.2 Questions for Chapter 1 1. Exqlhin the distinction betwee high levels and low levels, 2 What isa “black box"? 3. Name a few advantages to programming in the C language. ‘The compiler 3 2 Using a compiler How to use a compiler. What can go wrong. ‘The operating system is the layer of software that drives the hardware of a computer and provides the user with a comfortable work environment. Operating systems vary, but most Inve a shell, or text interface. ‘You use the GNU shell every time you type in a command ‘that launches an email program or text editor under GNU. In the following sections of this chapter, we will explore how to create a C progyam fiom, the GNU shell, and what might go wrong when you do, 2.1 Basic ideas about C First a note about a programming language that is different fiom the C programming, language, the GNU shell. When you enter commands in the GNU shell, they are executed immediately. Moreover, the shell is a programming language, in that the commands you type are a program, because you can also create a text file containing many shell cammands. ‘When you nin this file, the commands will be executed in sequence. On the other hand, consider C. While a shell command file can be executed directly, a C program must: be created in two stages 1. First, the program is written in the form of text files with a text editor such as GNU Emacs. This fom of the program is called the source code. A computer cannot execute source code directly. 2 Second, the completed source code is processed with a compiler — a program that generates a new file containing a machine-lnguage translation of the source code. ‘This file is called an executable file, or executable. The executable file is said to have been compiled from the source code, ‘To mm the compiled program, you must usually type the name of the executable file precded by a period and a slash, as in this example: -/uyprogram ‘The “dot-slash” prefix tells the GNU shell to look in the cument ditectory for the executable. ‘You usually do not need to type ‘./? in front of commands for programs that: came with your GNU system, such as emacs, because the computer already knows where to look for ‘the executables of those programs, which were placed in special directories when your GNU system was installed. A Cpregram is made up of, among other components, variables and fianctions. A variable is a way to hold some data which may vary, hence the name, For example, a variable might hold the mmber 17, and later the mumiber 41, Another variable might hold the word “Sue”. ‘A finetion is a segment of text in the soume code of a program that tells the computer what to do. Programming consists, in large part, of writing functions. 4 Chapter 2: Using a compiler 2.2 The compiler When you compile a program, the compiler usually operates phases called passes. The sequence happens approximately like this: an orderly sequence of 1. First, the compiler reads the source code, perhaps generating an intermediate code (such as pseudo-code) that simplifies the source code for subsequent processing, 2. Next, the compiler converts the intermediate code (if there is any) or the original source code into an object code file, which contains machine language but is not yet executable. The compiler builds a separate object file for each source file. These are only temporary and are deleted by the compiler after compilation. 3. Finally, the compiler runs a linker. The linker merges the newly-created object code with some standard, built-in object code to produce an executable file that can stand alone. GNU environments use a simple command to invoke the C compiler: gee, which stands for “GNU Compiler Collection”. (It used to stand for “GNU C Compiler”, but now GCC ean compile many more languages than just C.) Thus, to compile a small program, you will usually type something like the following command: gee filename On GNU systems, this results in the creation of an executable program with the default name ‘a.out’. To tell the compiler you would like the executable program to be called something else, use the ‘-o’ option for setting the name of the object code: gee -o program-name filename For example, to create a program called ‘myprog’ from a file called ‘myprog.c’, write gee -o myprog myprog.c ‘To launch the resulting program ‘nyprog’ from the same directory, type -/myprog, 2.3 File names GCC uses the following file name conventions: Source code file rogram.name.< Object file rogram.name.o Executable file program_name (no ending) Header file name-h Library file Libname.a or Libname.so ‘The file name endings, or file extensions, identify the contents of files to the compiler. For example, the .¢’ suffix tells the compiler that the file contains C source code, and the other letters indicate other kinds of files in a similar way. Errors 3 2.4 Errors Errors are mistakes that programmers make in their code. There are two main kinds of errors, © Compile-time errors are errors caught by the compiler. They can be syntax errors, such as typing fro instead of for, or they can be errors caused by the incorrect construction of your program. For example, you might tell the compiler that a certain variable is an integer, then attempt to give it a non-integer value such as 5.23. (See Section 2.4.2 [Type errors], page 6.) ‘The compiler lists all compile-time errors at once, with the line number at which each error occurred in the source code, and a message that explains what went wrong. For example, suppose that, in your file “eg.c’ you write y= sin (x); instead of y = sin (x); (By the way, this is an example of assignment. the equals sign (‘='), you are assigning the variable y (causing the variable y to contain) the sine of the variable x, This is somewhat different from the way equals signs work in mathematics. In math, an equals sign indicates that the numbers and variables on either side of it are already equal; in C, an equals sign makes things equal. Sometimes it is useful to think of the equals sign as an abbreviation for the phrase “becomes the value of”.) Ignore the syntactic details of the statements above for now, except to note that clos- ing the (x) with a square bracket instead of a parenthesis is an error in C, Upon compilation, you will sce something like this error message: eg.c: In function ‘main’: eg.c:8: parse error before ‘]’ (Ifyou compile the program within Emacs, you can jump directly to the error. We will discuss this feature later. See Chapter 23 [Debugging], page 223, for more information.) A program with compile-time errors will cause the compiler to halt, and will not produce an executable. However, the compiler will check the syntax up to the last line of your source code before stopping, and it is common for a single real error, even something as simple as a missing parenthesis, to result in a huge and confusing list of nonexistent “errors” from the compiler. This can be shocking and disheartening to novices, but you'll get used to it with experience. (We will provide an example later in the book, See Chapter 23 [Debugging], page 223.) ‘As a rule, the best way to approach this kind of problem is to look for the first error, fix that, and then recompile. You will soon come to recognize when subsequent error messages are due to independent problems and when they are due to a cascade. # Run-time errors are errors that occur in a compiled and running program, sometimes long after it has been compiled. One kind of run-time error happens when you write a running program that does not do what you intend, For example, you intend to send a letter to all drivers whose 6 Chapter 2: Using a compiler Ticenses will expire in June, but instend, you send a letter to all drivers whase licenses will ever expire, Another kind of run-time error can cause your program to crash, or quit abruptly. For example, you may tell the computer to examine a part of its memery that doosn’t exist, or to divide some variable by zero. Fortunately, the GNU environment is extremely stable, and very little will occur other than an emor message in your terminal window when you crash a program you are writing under GNU. If the compilation of a program is successful, then a new executable file is created. ‘When a programmer wishes to make alterations and corrections to a C program, these must be made in the source code, using a text editor; after making the changes, the pro- grammer must recompile the program, or its salient parts. 2.4.1 ‘Typographical errors ‘The compiler can scmetimes fail for very simple reasons, such as typographical exroms, including the misuse of upper and lower-case characters. The C language is casosensitive. Unlike languages such as Pascal and some versions of BASIC, C distinguishes between upper and lower-case letters, such as ‘A’ and ‘a’. Tf letter is typed in the wrong case in a Titical place in the source code, compilation wil fail. This is a potential source of errors ‘that are difficult to find. 2. Type errors C supparts a variety of variable types (different kinds of variables for different. kinds of data), such as integer for integer numbers, and float for numbers with fractional parts. ‘You can even define your own types, such as total for a sum, or sumame for somocne’s Jhst name. You can also comet a variable of cne type into other types. (This is called type coercion.) Consequently, the type of a variable is of great importanee to the compiler, C requires us to list the names and types of all variables that wall be used in a program, and provide information about where they are going to be used. This is called declaring variables. If you fail to declare a variable, or use it as if it were a different type from the type it is declared to be, for example, by assigning a nomintegpr value to an integer variable, you will receive a compile-time error. Soe Chapter 5 [Variables and declarations), page 19, for more information on variable declarations. See Chapter 3 [The form of a C program], page 9, for some simple examples of variable declarations. 2. 2.5 Questions for Chapter 2 1. What is a compiler? 2. How doos one rum a C program? 3. How does one usually compile a C program? 4. Are upper and lower case equivalent in C? 5. What the two main kinds of error that can occur in a program? Questions for Chapter 2 7 6. Ifyou had some C source code that you wished to call “accounts”, under what name ‘would you save it? 7. What would be the mame of the executable file for the program in the Tast question? & How would you run this program? Chapter 2: Using a compiler ‘A word about style 9 3 The form of a C program What goes into a C program? What does one look like? ‘The basic building blods of a C pgram is the fiction. Every C program is a collection of one or more functions. Functions are made of variable declarations and statements, or complex commands, and are surrounded by curly brackets (‘ and ‘¥). (One and only one of the fictions in a program must have the namemain. This fimction is always the starting point of a C program, s0 the simplest: C program is a single function definition: main © { } ‘The parentheses ‘()” that follow the name of the function must be included. This is how C ‘The fimetion main doos not need to be at the top of a program, 0 a C program doos not necessatily start at line 1, but wherever the fimetion called main is Iocated. ‘The function main cannot be called, or started, by any other fimction in the program, Only the operating system can call main this is how a C program is started. ‘The next most simple C program is perhaps a program that starts, calls a fimction that does nothing, and then ends, J anetentunnnvonta tens atenttestrenterertresttretetetteey] /* */ /* Program : do nothing */ i* +/ eoerrenreencercenrennnencereereererreeseereereeret ©? minO /* Nain program +/ { do_nothing() ; + FERRERS EIEIO EOI I II RAIA do-notningO /* Function called */ + (Any text sandwiched between ‘/ and 4/” in C code is a comment: for other humans to read. See the section on comments below for more information.) ‘There are several things to notice about this program. First, this program consists of two fianctions, one of which calls the other. Socand, the fimction do_notihing is called by simply typing the main part of its name followed by ‘©’ parentheses and a semicolon. ‘Third, the semicolon is vital; every simple statement in C ends with one, This isa signal to the compike that the end of a statement has been reached and that anything that follows is part of another statement. This signal helps the compiler diagnose errors. 10 Chapter 3: The form ofa C program Fourth, the curly bracket characters *{° and ‘} outline a block of statements. When ‘this program meets the closing ‘¥’ of the socand fimction’s block, itt transféas control back to ‘main’, where it meets another 4’, and the program ends. 3.1 A word about style ‘The code examples above are simple, but they iustrate the control flow of a C program, or the order in which its statements are executed. You should note that these programs are written in “old-fashioned” C, as the language existed before ANSI Standard C—the version in which most C! programs are now written. The above programs are also missing several ey elements that most C programs have, such as header files and function prototypes. Finally, they do not show good styl; if you wish to submit programs you write to the Free Software Foundation, you should consult its advice on how best to use the C language. ‘You may wonder why we chose oldstyle C for those first few examples, even though people proverbially learn best: what they learn first. We did so because pre-ANSI C is con- siderably simpler than the present form, and also because as you develop as a C programmer, you will probably run across some old C code that you will want to ead. ‘You may ako wonder why a savvy programmer would want to follow the ANSTStandard, which was drafted by committee, ar even the GNU guidelines, Isn't programming fee software all about freedom? Yes, but following the ANSI Standard ensures that: your code can be easily compiled on many other computer platforms, and the GNU guidelines ensure ‘that your code can be read by other programmers (We wil introduce good C style in our examples soon. Meanwhile, you can examine the GNU guidelines later in the book. See Chapter 22 [Style], page 219.) 3.2 Comments Annotating programs. Comments are a way of inserting remarks and reminders into code without affecting its behavior. Since comments are only read by other humans, you can pat anything you wish to in a comment, but it is better to be informative than humorous. ‘The compiler igneres comments, treating them as though they were whitespace (blank: Guaracters, such as spaces, tabs, or carriage returns), and they are consequently ignored. During compilation, camments are simply stripped out of the code, so programs can contain any number of comments without losing speed. Bocarse a comment is treated as whitespace, it can be plaood anywhere whitespace is valid, even in the middle of a statement. (Such a practice can make your code difficult to read however.) Any text sandwiched between ‘/#” and %/ in C code is a comment. Here is an example ofa C comment: Pee Questions for Chapter 3 u Comments do not necessarily temninate at the end of a line, only with the characters 47 TE you forget to close a comment: with the characters °/°, the compiler will display an. ‘untemminated coment’ error when you try to compile your code. 3.3 Example 1 #include /* header file +/ min Q /* Trivial program +/ { /* This little line has no effect +/ /* This little line has none +/ /* This little line went all the way dom. to the next line, do_littleQ; printf ("Function ‘main’ completing.\n"); } GRR pope pepeienpeienprpennnpennnnnpensnprperss / /* A bar Like the one above can be used to +/ /* separate functions visibly in a program */ do.little © { /* This function does little. +/ printf ("Function ’do_little’ completing.\n"); + “Again, this example is cldefashioned C; and in mediocre style, ‘To make it more ccmpliant with the ANSI Standard and GNU guidelines, we would declare the variable type each fiction returns (int for main, which ako requires an exit or retum statment), and we ‘would create function prototypes at the beginning of the file. (See Chapter 4 [Functions], page 13.) 3.4 Questions for Chapter 3 1. What is a block? 2 Does a C program start at the beginning? Wher is the beginning? 2 Chapter 3: The form ofa C program 3 What happens when a program comes to a 9° character? What does this character Nee 4, What vital pioce of punctintion gpes at the end of every simple C statement? 5. What happens if a comment is not ended? ‘That is if the programmer typos ‘/#? «to start but forgets the .°#/° to cle? Funetion examples 13 4 Functions Solving problems and getting results. A function is a section of program code that performs a particular task. Making funetions is a way of isolating one section of code from other independent sections. Funetions allow a programmer to separate code by its purpose, and make a section of code reusable — that is, make it so the section can be called in many different contexts. Functions should be written in the following form: type function.name (type parameterl.name, type parameter2.name, .. t variable declarations statements + ‘You may notice when reading the examples in this chapter that this format is somewhat different from the one we have used so far. This format conforms to the ANSI Standard and is better C. The other way is old-fashioned ©, although GCC will still compile it Nevertheless, GCC is not guaranteed to do so in the future, and we will use ANSI Standard C in this text from now on. As shown above, a function can have a number of parameters, or pieces of information from outside, and the function's body consists of a number of declarations and statements, enclosed by curly brackets: ‘{...}. 4.1 Function names Every function has a name by which it is known to the rest of the program. The name of a function in C can be anything from a single letter to a long word. The ANSI Standard, however, only guarantees that C will be able to distinguish the first 31 letters of identifiers, or function and variable names. (Identifiers are therefore said to have 31 significant characters.) In some cases, identifiers may have as few as six significant characters, to stay compatible with older linkers, but this part of the ANST Standard is becoming obsolete, A function name must begin with an alphabetic letter or the underscore but the other characters in the name can be chosen from the following groups: > character, * Any lower-case letter from ‘a’ to ‘z" # Any upper-case letter from ‘A? to ‘2 © Any digit from ‘0° to ‘9° © ‘The underscore character ‘_ Note that with GCC, you can also use dollar signs (‘$") in identifiers. This is one of GCC’s extensions to the C language, and is not part of the ANST standard. Tt also may not be supported under GCC on certain hardware platforms. u (Chapter 4: Functions 4.2 Function examples Here isan example of a finction that. adds two integers and prints the sum with C’s “print formatted” function named printé, using the characters “4d to specify integer output. void add_tvomumbers (int a, int b) /s Add a and b +/ { int ¢; cratd; printf ("ia\n", os a ‘The variables a and b are parameters passed in from outside the fimction. ‘The code defines a,b, and c to be of type dint, or integer, ‘The function above is not much use standing alone, Here is a main function that calls the add_two numbers fisnction: int main() { int vart, var2; vari = 4; var2 = 53; add_two_numbers (vari, var2); add_two_numbers (1, 2); exit(O); + ‘When these fictions are incorporated into a C program, together they print the number 54, then they print the mumber 3, and then they stop. 4.3 Functions with values In mathematics, a function takes one or more values and calealates, or returns, another value, In C, some fimctions retum values and others do not; whether a. fimction you write does ar does not will depend on what you want the function to do, Far example, a function ‘that caleulates a value should probably refum that value, while a fimction that merely prints something out may not need to. ‘The add_two_mumbers function above did not retum a value. We will now examine a fmetion that does. Here is an example of calling a fimetion that returns a value: bill = calculatebill Gatal, data2, data3); ‘When this statement is executed, control is passed to the function calculate_bil1, that function executes, and then it retums control and some value to the original statement, ‘The value retumod is assigned to bi11, and the program continues. In G, retuming a value fom a fimction is a simple matter. Consider the fimetion calculatebill as it might be written in a program that contains the statement above: Function prototyping 15 int calaulate_bill (int a, int b, int c) { int total; total =a+b+c; return total; + As soon as the return statement is met, callculate_bill stops executing and returns the value total. A function that returns a value must have a return statement. Rargetting it can ruin a program. For instance if calculate_bill had 1ead as follows, then the variable bi11 would have had no meaningful value assigned to it, and you might have received a waming from ‘the compiler as well. (The word void below indicates that the fimction does not retum a value, In ANSI C, you must place it before the name of any such function.) ee calculate_bill (int a, int b, int c) int total; total=atb+c; + On the other hand, you do not need to actually use a value when a fimction retums one. For example, the C input/output functions printf and scanf retum values, but the values are rarely used. See (undefined) [files], page (undefined), for more information on thaw fimetions. If we we the first version of the calculate_bil1 fimetion (the one that contains the ine return total;), the value of the fimction can simply be discarded. (Of comso, the resulting program is not very useful, since it never displays a value to the user!) int main() { calculate_bill (1, 2, 3); exit (0); + 4.4 Function prototyping Fimctions do not have to return integer values, as in the above examples, but can return almost any type of value, including floating point and character values, (Sce Chapter 5 [Variables and declarations], page 19, for more information on variable types.) ‘A fimction mmst be dedared to retum a certain variable type (such as an integer), Just as variables must be, (See Chapter 5 [Variables and declarations), page 19, for more information about variable types.) To write code in good C style, you should declare what type of value a fimetion retums (and what type of parameters it accepts) in two placas 1. At the beginning of the program, in global scope. (Gee Chapter 6 [Soope], page 27.) 2. In the definition of the fimetion itself, Finetion decrations at the beginning of a program are called prototypes. Here i an. example of a program in which prototypes are used: 16 Chapter 4: Functions #include void print_stuff (int foo, int bar); int calcvalue (int bas, int qx); void print_stuff (int foo, int bar) { int var_to_print; var_to_print = calc_value (foo, bar); printf ('var_to_print = d\n", var_to_print); + int calcvalue (int bas, int quux) { retum bas * qux; + int main() { Print_stuff (23, 5); exit (©); + ‘The above program will print the text ‘var touprint = 1167 and then quit. Prototypes may seem to be a nuisance, but they overcome a problem intrinsic to cam pilers, which is that they compile functions as they come upon them. Without function prototypes, you usually cannot write code that calls a fimction before the fiction itself is defined in the program. If you place prototypes for your functions in a header file, however, you can call the fimctions from any source code file that includes the header, This is one reason C is considered to be such a flexible programming language. Some compilers avoid the use of prototypes by making a first pass just to see what fimetions are there, and a second pass to do the work, but this takes about twice as long. Programmers already hate the time compiles take, and do not want to use compilers ‘that make unnecessary passes on their source code, making prototypes a necessity, Ako, prototypes amble the C compiler to do more rigorous er checking, and that saves an enormous amount of time and grief. 4.5 The exit function GNU ending standards specify that you should always use exit (or retumn) within your main fimetion, (See Chapter 2 [Style], page 219.) ‘You can use the exit fimction to terminate a program at any point, no matter how many fimction calls have been made, Before it terminates the program, it calls a: number of other fumetions that perform tidy-up duties such as dosing open files. Questions for Chapter 4 wv exit is called with a return code, like this: exit); Jn the example above, the retum code is 0. Any program that calls your program can read ‘he retum code from your program. ‘The retum code is like a return value fiom another function that: is not main in fact, most of the time you can use the retumn command within ‘your main, instead of exit. Conventionally, a return code of 0 specifies that. your program has ended normally and all s well. (You Gan remember this as ‘Zero errors”, although for technical reasons, you cannot use the umber of errors your program found as the return code. See Chapter 22 {Sty}, page 219.) A retum codecther than 0 indicates that some sort of error has occured. Tf your code terminates when it encounters an error, use exit, and specify a nonzero retumn code, 4.6 Questions for Chapter 4 1. White a fimetion that takes two values a and b, then retums the value of a * b (that isa times.) 2 Ts there anything wmong with a fimetion that returns no value? 3. What happensifia fimetion returnsa value but you do not assign that value to anything? 4. What happens if a variable is assigned the result of a fimetion, but: the fimetion does not retum a value? 5. How can you make a program temninate, anywhere in the program? Chapter 4: Functions Tnteger variables 19 5 Variables and declarations Storing data. Discriminating types. Declaring data, ‘Variable names in C follow the same rules as fimetion names, as far as what characters ‘they can contain. (See Section 4.1 [Function names], page 13.) Variables work differently from fimctions, however, Every variable in C has a data type or type, that camveys to the ‘he compiler what sort of data will be stored in it. Functions in C are sometimes said to ave types, but a fimetion’s type is actually the data type of the variable it returns. Tn some older computer languages like BASIC, and even some newer ones like Perl, you can tell what type a variable is because its name begins or ends with a special character. Foreampk, in many versions of BASIC, all integer variable namas end with a percent sign (e) — for example, “YEAR?. No such convention exists in C. Thstead, we declare variables, or tell the compiler that they are of a certain type, before they are used. This feature of G has the following advantages (among others): It gives a compiler precise information about the amount of memory that will have to be allotted to a variable when a pmgram is nin, and what sort of arithmetic will have to be wed with it (@g, integer, floating point, ar none at all). © It provides the compiler with a list of the variables so that it can catch errors in the code, such as assigning a string to an integer variable, ‘There are a Dot of variable types in C. Tn fact, you can define your own, but there are some basic types ready for use, We will discuss them in the following sections, 5.1 Integer variables Chas five kinds of integer. An integer isa whole number (a number without a fractional part). Tn, there are a limited mumber of integers possible; how many depends on the type of integer. In arithmetic, you can have as large a number as you like, but. C integer types always have a largest (and smallest) possible mnmber, © char: A single byte, usmlly one ASCII character. (Soo the section on the char type below.) © short: A short integer (16 bits Jong on mest GNU systens). Abo called short int. Rarely used. © int: A standand integer (32 bits long on most GNU systems). Long: A Jong integer (32 bits Jong on most GNU systems, the same as int). Also called ‘ong int. Long Long: A Jong Jong integer (64 bits Jong on most, GNU systems). Alo called long long int. G4-bit operating systems are now appearing in which long integprs are 64 bits lang, With GOG, long integers are normally 32 bits long and long long integers are 64 bits long, but it varies with the computer hardware and implementation of GCC, so check your system's documentation, ‘These integer types differ in the size of the integer they can hold and the amount. of storage required for them, ‘Thesizes of these variables depend on the hardware and operating 20 Chapter 5: Variables and dechrations system of the computer. On a typical 32-bit GNU system, the sizes of the integer types are as follows. ‘Type Bits Possible Values char 8 “127 to 127, unsigned char 8 0 to 255, short 6 -32,767 to 32,767 unsigned short 16 0 to 65,535 int 2 “2M ABBGAT to 2y1A7AR3,647 unsigned int 3 0 to 4,294,967,295, lang 2 -2,MM7A83,647 to 2y1A7AS3,647 unsigned long 32 0 to 4,204,967,295 ‘long long 64 -9,223,372,0136,854,775,807 to 9. SATS: unsigned longlong 64 Oe THETA SL 615 Onseme computers, the lowest possible value may be 1 Jess than shown here; for example, the smallest possible short may be «32,768 rather than «32,767. ‘The word unsigned, when plaood in front of integer types, means that only pasitive or zero values can be used in that variable (ie. it cannot have a minus sign). The advantage is that larger numbers can then be stored in the same variable, The ANSI standard ako allows the word signed to be placed before an integ=r, to indicate the opposite of unsigned. 5.1.1 The char type char is a special integer type designed for storing single characters. The integer value of a char corresponds to an ASCII character. For example, a value of 65 comesponds to the Tetter “A°, 66 comesponds to ‘8’, 67 to ‘C’, and 0 on. As in the table above, unsigned char permits values from 0 to 255, and signed char pemnits valwes from -127 (or -128) to 127. The char type is signed by default. an some computers, but unsigned.on othens, (See Appendix E [Character conversion table}, page 249. See Appendix D [Special characters}, page 247.) char is used only within arays; variables meant to hold one character should be declared. int. (See Chapter 15 [Strings], page 101, for more information on character arrays, See Section 5.4.1 [Cast operator demo}, page 23, for an example of how to use an integer variable to bold a character value.) 5.1.2 Floating point variables Floating point numbers are mmbers with a decimal point. There are different sizes of floating point. numbers in C. The float type can contain large floating point: numbers with a small degree of precision, but the doubl-precision double type can hold even larger Declarations 21 numbers with a higher degree of precision. (Precision is simply the number of decimal places to which a number can be computed with accuracy. If a number can be computed to five decimal places, it is said to have five significant digits.) All floating point mathematical functions built into C require double or long float. arguments (Long float variables are generally the same as double variables on GNU sys- tems), so it is common to use float only for storage of small floating point numbers, and to use double everywhere else. Here are the floating point variable types available in C: © float: A single-precision floating point number, with at least 6 significant decimal digits * double: A double-precision floating point number. Usually the same as long float on GNU systems. Has at least 10 significant decimal digits. © ong double: Usually the same as double on GNU systems, but may be a 128-bit number in some cases. On a typical 32-bit GNU system, the sizes of the different floating point types are as follows. ‘Type Bits Possible values (approx.) float 32 Le-38 to 1e+38 double 64 260-308 to 1e+308 ong double 64 260-308 to 1e+308 ‘You may find the figures in the right-hand column confusing. They use a form of short= hand for large numbers. For example, the number 5e2 means 5 + 10°2, or 500, 5e-2 means 5+ 10° ~ 2 (5/100, or 1/20). You can see, therefore, that the float, double, and long double types can contain some very large and very small numbers indeed. (When you work with large and small numbers in C, you will use this notation in your code.) 5.2 Declarations To declare a variable, write the type followed by a list of variables of that type: typename variablename.t, ..., variablename.n; For example: int last_year, cur_year; long double earth_mass, mars_mass, venus_mass; unsigned int num_pets; long city_pop, state_pop; state_pop = city_pop = 5000000; short moon_landing = 1969; 2 Chapter 5: Variables and declarations float tempt, temp2, temps; “Always declare your variables A compiler will catch a missing declaration every time and ‘terminate compilation, comphining bitterly, (You wall often see a hast of error messagps, one for each use of the undeclared variable. See Chapter 23 [Debugging], rage 223.) 5.3 Initialization Assigning a variable its fins value is called initializing the variable. When you declare a variable in C, you can also initialize it at the same time. ‘This is mo more efficient in terms of a ruming program than doing it in two stages, but sometimes creates tidier and more compact code, Consider the following: int initial year; float percent _complete; initial_year = 1969; percent_conplete = 89.53 ‘The code above is equivalent to the code below, but the code below is more compact. int initial _year = 1969; float percent_complete = 89. ‘You can always write declarations and initializes this way; but you may not always want to, (See Chapter 22 [Style], page 219.) 5.4 The cast operator An operator is a symbol or string of C characters used as a function. One very valuable operator in C is the cast operator, which converts one type into another. Its general form isas follows: (type) variable For cumple, floating point and integer types can be interamverted: float exact_length; int rough_length; exact.length = 3.37; rough_length = Gint) exact_length; Jn the example above, the cast operator rounds the number down when converting it from a float to an integer, because an integer number cannot represent the fractional part after the docimal point. Note that C always truncates, or rounds down, a number when converting it to an integ. For example, both 3.1 and 3.9 are truncated to 3 when C is converting ‘them to integer values, Cast operator demo B ‘The cast operator works the other way around, too: float exact_length; int rough_length; rough_length = 12; exact_length = (float) rough length; Tn converting large integers to floating point numbers, you may lose some precision, since the float type guarantees only 6 significant digits, and the double type guarantees only 10. Tt docs not always make sense to convert types. (See Chapter 20 [Data structures}, page 197, for examples of types that do not convert to other types well) 5.4.1 Cast operator demo ‘The following is an example of how to we the cast operator in C code, Tt also shows how to use an integer variable to store a character value, _peeaebeoneboonaoconaocrbaaeroanaocainaea eat i / 7 Deno of Cast: operator */ i* */ sop eo dbp bra aoo ooo ipbbaaddoaaaopnnsssppaaaaoenes / #include int main() /* Use int float and int +/ { float my_float; int myint; int’ my_ch; my_float = 75.345; my_int = Gint) my_float; ny_ch = (int) my_float; printf ("Convert from float my_float-/f to my_int=/d and my_ch=Zc\n", myfloat, myaint, my.ch); nyaint = 695 ny_float = (float) my_int; ny_ch = my_int; printf ("Convert from int myint=/a to my_float=/f and myach=ic\n", my_int, my_float, my_ch) ; =e; nyaint = myich; my_float = (float) my_ch; printf ("Convert from int mych=c to myaint=/d and myfloat=/£\n", my_ch, my_int, my_float); mh Chapter 5: Variables and declarations exit(O); } Here is the sort of output you should expect (floating point values may differ slightly): Convert from float my_float=75.345001 to my_int=75 and my_ch=K Convert from int my_int=69 to my_float=69.000000 and my_ch=E Convert from int my_ch=* to my_int=42 and my_float=42.000000 5.5. Storage classes ‘There are a few variable declaration keywords commonly used in C that do not specify variable types, but a rated concept called storage classes. Two common examples of storage Class specifiers are the keywords extern and static. 5.5.1 External variables Sometimes the source code for a C program is contained in more than one text file. Tf this is the ca, then it may be nowssry to use variables that: are definod in another file. ‘You can usea globall variable in files other than the one in which its defined hy mededlaring it, prefixed by the extern specifier, in the other files, File maine File secodarysc ttinclude int my_var; int main() { extern int my_var; void print_value( { my.var = 500; print# ("my_var = Yd\n", my_var); print_value(); + exit (0); + Jn this example, the variable my_var is created in the file ‘secondary.c’, assigned a value in the file ‘main.c’, and printed out in the fiction print_value, which is defined in the file ‘secondary .c’, but called from the file ‘main.c’, Soe Section 174 [Compiling mitiple files], page 166, for information on how to compile a program whose source code is split among multiple files. For this example, you can simply type the command gcc -o testprog main.c secondary.c, and run the program with ./testprog. 5.5.2 Static variables ‘A second important storage class specifier is static. Normally, when you call a finction, all its local vatiables are reinitialized each time the function & called. This means that, ‘their values change between fimction calls. Static variables, however, maintain their value Dbetwoen fimction calls, Exay global variable is defined as static automatically. (Roughily speaking, fimetions anywhere in a program can refer to a global variable; in contrast, a fimction can only Questions for Chapter 5 B refer to a local variable that is “nearby”, where “nearby” is defined in a specific manner. Soo Chapter 6 [Scope], pagp 27, for more information an global variables. See Chapter 7 [Expressions and operators], page 31, for an example of a static local variable.) 5.5.3 Other storage classes ‘There are thre more storage class identifiers in C: auto, register, and typedef. @ auto & the opposite of static. It is redundant, but is induded in contemporary versions of C for backwards compatibility. AI! local variables are auto by default. © register is another outdated C storage class. Defining a variable as register wed to store it in one of the computer's registers, a specific location on its processar chip, ‘thaehy making code using that variable run faster. These days, most C compilers (ending GOC) are smart enough to optimize the code (make it faster and more compact) without the register keyword. © typedef allows you to define your own variable types. See Chapter 19 [More data types], page 189, for more information, 5.6 Questions for Chapter 5 1. What is an identifier? 2. Which of the following are valid C variable names? 1. Ralph23 2 80shilLings 3. mission_control 4 5 AS 6. off Wiite a statement to dechre two integers called start_temperature and end_temperature, ‘What is the difference between the types float and double? ‘What is the difference between the types int and unsigned int? Write a statement that assigns the value 1066 to the integer variable norman, ‘What data type do C functions retum by default? ‘You must declare the data type a function returns at: two places in a program, Where? ‘White a statement, using the cast operator, to print out the integer part of the number 23.1256, 10, Is it possible to have an automatic global variable? Pa Sen ene Chapter 5: Variables and dechrations Local Variables og 6 Scope Where a program’s fingers can and can't reach. Imagine that a function is a building with a person (Fred) standing in the doorway. ‘This person can see certain things: other people and other buildings, out in the open, But Fred cannot see certain other things, such as the people inside the other buildings. Just so, some variables in a C program, like the people standing outside, are visible to nearly every other part of the program (these are called global variables), while other variables, like the people indoors, are hiiden behind the “bridk walls” of curly brackets (these are called Jocal variables). Where a variable is visible to other C code is called the scope of that variable, There are two main kinds of scope, global and local, whidh stem from the two kinds of places in which you can declare a variable: 1. Global scope ' outside alll of the fimctions, that is, in the space between function definitions — after the #include lines, for example, Variables declared in global scope. are called global variables, Global variables can be used in any fimction, as well as in any block within that function, include int global_integer; float global_floating_point; int min © { exit (0); 3 2 You can also declare variables immetiately following the opening bracket (() of any lock of code, This area is called Jocal scope, and variables declared here are called Jocal variables, A local variable is visible within its own block and the ones that block contains, but invisible outside its own block. #tinclude int main() { ant £003 float bar, bas, quux; exit (0); + 6.1 Global Variables Global variables can be used in any function, as well as any block within that fimction, (Tedinically, global variables can only be seen by functions that are defined after the dec Tnation of those global variables, but global variables are usually decdared in a header file that is included everywhere they are neoded.) Global variables are created when a program is started and are not destroyed until a program is stopped. 8 Chapter 6: Seope 6.2 Local Variables Local variables, on the other hand, are only visible within Jocal scope, ‘They are “rapped” inside their code blodss, Just as global scope contains many functions, however, each function can contain many code blocks (defined with amly brackets: “{...}). C allows blocks within blodss, even functions within functions, ad énfinitum. A local variable is visible within its own blods and ‘the ones that block contains, but invisible outside its own block, int a; /* Global scope. Global variable ’a’ is visible here. but not local variables ’b? or ’c?. +/ int main() { ant bs /* Local. scope of *main’. Variables ’a’ and ’b’ are visible here, but not co’. */ { int ¢; ‘/* Local scope of ‘{...}? block within ’min?. Variables ’a’, *b?, and ?c? are all visible here. */ + exit (0); + Local variables are not visible outside their curly brackets. ‘To use an “existenax” rather ‘hana “visibility” metaphor, local variables are created when the opening brace is met, and ‘they are destroyed when the dlasing brace is met. (Do not take this too literally; they are not created and destroyed in your C source code, but intemally to the computer, when you run the program.) 6.3 Communication via parameters Tf mo cnde inside a fimetion could ever commmnicate with other parts of the program, ‘then fimctions would not be very useful. Fictions would be isolated, comatose, unable to do much of anything, Fortunately, although local variables are invisible outside their code blodks, they cn still conmmmicate with other functions via parameters. See Chapter 7 [Expressions and operators], page 31, the next chapter, for information on parameters. 6.4 Scope example Notice that thew are two variables named my.var in the example below, both visible in the same place, When two or more variables visible in one area of code have the same Questions for Chapter 6 » name, the last variable to be defined takes priority. (Technically adept readers will realize that this is because it, was the last. one onto the variable stack.) _Heado bane aaddo nab paid nna aac REA / i* */ /* SCOPE */ i* */ HERERO AAR R IE EIAA AOR AAA AREA III / #include int min { int my_var = t aint my_var = 53 printf ("ny_var-Za\n", my_var); 3 printf (ny_varZd\o", my_var) ; exit (0); } ‘When you run this example, it will print out the following text: my_var=5 my_var=3 6.5 Questions for Chapter 6 1. What is a globall variable? 2 What sa local variable? 3. Do parameters spoil functions by leaking the variables into other fimetions? 4, White a program gnoahs_park that declares 4 variables, Two global integer variables called num_gaus and mun_gnats, and two Jon! floating point variables within the func- tion mein, called avg_gnu_mass, and avg.gnat.mass. Then add another fiction called calculate_park_biomass, and pass avg_gnu_mass and avg_gnat_mass to it. ‘How many different storage spaces are used when this program runs? (Hint: are avg. gnu_nass and avg_gnat_mass and their copies the same?) ‘Chapter 6: Scope ‘The assignment operator aL 7 Expressions and operators ‘Thinking in C. Short strings of code. ‘An operator is a character or string of characters used as a built-in fimetion, We have already experimented with one operator in C: the cast operator. ‘An operator is so called because it takes one or more vals and operates on them to produce a result. For example, the addition operator + can operate on the values 4 and 5 to produce the result 9, Such a procedure is called an operation, and any value operated on (such as 4 and 5 in this example) is called an operand, ‘There are many operators in C, Some of them are familiar, such as the addition operator + and subtraction operator =. Most operatars can be thought of as belonging to one of three groups, according to what they do with their operands: ©. Mathematical operatons, such as the addition operator + in 100 + 500, or the mnltiphi- cation operator * in 12 * 2, © Comparison operators (a subset of mathematical operators), such as the Jes-than op- ezator . © Operatons that produce new variable types, such as the cast operator. ‘The majority of operators fall into the first group. The second group is a subset of the first sets in this second set, the result of an operation is a Boolean value (a value of either true or filse). Cins about forty different operators, The chief object of this chapter is to explain the basic operators in C. We will ewmine more complex operators in another chapter. (See Chapter 18 [Advanced operators}, page 177.) 7.1 The assignment operator No operator such as addition (+) or multiplication (#) would be usefil without another operator that attaches the values they produce to variables. Thus, the assignment operator = is perhaps the most important mathematical operator. ‘We have seen the assignment operator already in our code examples, Here is an example to refiesh your memery: int gnu_count, gnat_count, critter_count; gm_count = 45; nat_count = 5678; critter_count = gnucount + gnat_count; ‘The assignment operator takes the value of whatever is on the right-hand side of the = symbol and puts it into the variable on the left-hand side, For example, the code sample above assigns the value 45 to the variable gnu_count. ‘Something that can be assigned to is called an Ivalue, (“1 for “eft”, because it can appear on the deft side of an assignment), You will sometimes see the word ‘value’ in error messages fitm the compiler. For example, try to compile a program containing the {following code: 32 Chapter 7: Expressions and operators 5243; You will receive an error such as the following: bad_example.c:3: invalid Ivalue in assignment ‘You can't assign a value to 5; it has its own value already! In other words, 5 is not an value, 7.1.1 Important note about assignment Many people confuse the assignment operator (=) with the equality operator (==), and this is a major source of bugs in C programs. Because of early arithmetic training, people tend to think of = as indicating equality, but in C it means “takes on the value produced by”, and it should always be read that way. By way of contrast, == is an equality test operator and should always be read ‘is tested for equality with”. (See Section 7.8 [Comparisons and operator.) 7.2 Expressions and values ‘The most common operators in any language are basic arithmetic operators. In C, these include the following: + unary plus, example: +5 - unary minus, example: -5 + addition, example: 2+ 2 - subtraction, example: 14 - 7 + multiplication, example: 3+ 3 / floating point division, example: 10.195 / 2.4 / integer division div, example: 5 / 2 t integer remainder mod, example: 24 % 7 7.3 Expressions An expression is simply a string of operators, variables, numbers, or some combination, that can be parsed by the compiler. All of the following are expressions: 19 1+243 my_var my_var + some_function() (ny_var + 4 + (some_function() + 2)) Parentheses and Priority 33 32 * circumference / 3.14 day_of month % 7 ‘Here is an example of some arithmetic expressions in Ct include int main () { int my_int; printf (“Arithmetic Operators:\n\n"); ny_int = 6; printf ("ny_int = Yd, -ny_int = Yd\n", my_int, -my_int); printf ("int 1+ 2 = Ya\n", 1+ 2); printf ("int 5 - 1 = Ya\n", 5 - 1); printf ("int 5 * 2 = Yd\n", 5 * 2); printf (""\n9 div 4 = 2 reminder 1:\n"); printf (int 9 / 4 = Yd\n", 9 / 4); printf ("int 9% 4 = Yd\n", 9% 4); printf ("double 9 / 4 = %f\n", 9.0 / 4.0); retum 0; 3 ‘The program above produces the output below: Arithmetic Operators: ny.int = 6, -my.int = 6 int 1+2=3 int 5-124 int 5 * 2= 10 9 div 4 = 2 reminder 1: int 9/4=2 int 9%4=1 double 9 / 4 = 2.250000 7.4 Parentheses and Priority Just as in algebra, the C compiler considers operators to have certain priorities, and eval uates, or parses, scme operators before others. The order in which operators are evaluated is called operator precedence or the order of operations, You can think of some operatans as “stronger” tha others The “stronger” ones will always be evaluated firsts otherwise, expressions are evaluated from left to tight. uh Chapter 7: Expressions and operators For example, since the multiplication operator * has a higher priority than the addition operator + and is therefore evaluated first, the following expression will always evaluate to 10 rather than 18 44243 However, as in algpbra, you can use parentheses to forve the program to evaluate the expression to 18: G+ 3 ‘The parentheses force the expression (4 + 2) to be evaluated first. Placing parentheses around 2 * 3, however, would have no effoct. Parentheses are clawed as operatons by the compiler; they have a value, in the sense ‘that they assume the value of whatever is inside them. For example, the value of (S +5) is 10. 7.5 Unary Operator Precedence ‘Unary operators are operators that have anly a single operand — that is, they operate on only one object. The following are (or can be) all unary operaton= woe ‘The order of evaltntion of unary operators is fitm right to left, so an expression like: aptrt; ‘would perform the ++ before the *. (The ++ operator will be introduced in the next section, and the « operator will be introduced in the next chapter. Soe Chapter 9 [Pointers], page 45.) 7.6 Special Assignment Operators ++ anc has some special operators that can simplify code, ‘The simplest of thee are the ‘increment, and decrement operators: 4 increment: add one to - decrement: subtract one from ‘You can use these with any integer or floating point variable (or a character in some cases, carefully). They simply add or subtract 1 fiom a variable. The following three statements are equivalent: variable = variable + 1; variableH+; +Hvariable; So are these three: variable = variable variable; --variable; Notice that the + and -- operators can be placed before or after the variable, In the cases above, the two forms work identically, but there is actually a subtle difference. (See Section 18.1.2 [Postfix and prefix ++ and -}, page 179, for more information.) 45 ‘Mare Special Assignments 35 7.7 More Special Assignments Like ++ and ==, the following operators are short ways of writing Jonger expressions, Consider the following statement: variable = variable + 23; Th G this would be a long-winded way of adding 23 to variable. Tt could be done more simply with the general increment operator 45, as in this example: variable += 23; ‘This performs exactly the sume operation. Similarly, the following two statements are equivalent: variablel = variablel + variable2; variable1 += variable2; ‘There are a handful of these operators. For example, one for subtraction: variable = variable - 42; variable -= 42; ‘More surprisingly, perhaps, there is one for nuiltiplication: variable = variable + 2; variable += 25 ‘The main arithmetic operators all follow this pattem: a addition assignment operator subtraction assignment operator multiplication assignment operator i= division assignment operator (floating point and integers) te remainder assignment operator (integers only) ‘There are mare exotic kinds too, used for machine-level operations, which we will ignore for the moment. (Sce Chapter 18 [Advanced operators], page 177, if you want to know mare.) Here is a short program that demonstrates these special assignment operators: #tinclude int main() { int my_int; printf ("Assignment Operators:\n\n"); my_int = 10; /x Assignment, */ printf ("ny_int = 10 : Ya\n",my_int); ny_int++5 /+ my_int = my_int + 1 +/ printf ("nylint++ + %a\n",my.int); my_int 4 55 /* my_int = my_int +5 */ 36 Chapter 7: Expressions and operators print (myint 4= 5 : Ya\o"",my_int); ny_int—3 /* ny_amt = my_int = 1 +/ printf (ay_int— — : Ya\n",my_int); myeint ~= 25 /* myaint = my.int ~ 2 +/ printf ("my_int -= 2 : Yd\n"my_int); my_int = 5; /* my_int = my_int * 5 +/ printf ("my_int = 5 : %d\n",my_int); my_int /= 25 /* wyy_imt = my_int / 2 +/ printf ("mycint /= 2: 7a\n",myaint); mynint %= 33 /* mynint = my.int % 3 +/ printf (ny_int “= 3 : %d\n",my_int); retum 0; + ‘The program above produces the output below: Assignment Operators: 10 1 16 15 = 10 Ht +5 2:13 6 32 2 ‘The second to last line of output is my_int /= 2 : 32 Jn this example, 65 divided by 2 using the /= operator results in 32, not 325, ‘This is Decause both operands, 65 and 2, are integers, type int, and when /= operates on two inteae, it produces an integer result. This example only uses integer values, since that is how the mumbers are declared, To get the fractional answer, you would have had to declare ‘he three mumbers involved as floats. ‘The last line of output is pint t= 3 ‘This is becamse 32 divided by 3 is 10 with a remainder of 2. 7.8 Comparisons and logic Comparison operators tell you how numerical values relate to one another, such as whether they are equal to one another, or whether one s greater than the other. Comparison. operators are wed in logical tests, such as if statements. (Soe Chapter 10 [Decisions], Page 53.) Logical operators 37 ‘The results of a logical comparison are always either true (1) oF false (0). In computer programming jargon, true and fake are the two Boolean values. Note that, unlike real life, there are no “gray areas” in C; just as in Aristotelian logic, a comparison operator will never produce a value other than true or false. Six operators in C are used to make logical comparisons: BS equal to is not equal to > is greater than < is less than is greater than or equal to is les than or equal to Important: Remember that many people confuse the equality operator (=) with the as- signment operator (=), and this is a major source of bugs in C programs. (See Section 7.2 ons and values], page 32, for more information on the distinction between the and = operators) ‘The operators above result: in values, mmch as the addition operator + does They produce Boolean values: true and false only. Actually, C uses 1 for “true” and 0 for “falsc” when evaltuating expressions containing comparison operators, but it is easy to define the strings “TRUE? and ‘FALSE’ as macros, and they may well already be defined in a brary file you are using. (See Chapter 12 [Preprocessor directives], page 71, for information on defining macros.) define TRE 1 define FALSE 0 Note that although any nonzero value in Cis treated as true, you do not need to worry: about a comparison evahiating to anything other than 1 or 0. ‘Try the following short program: ttinclude int main () { int truth, falsehood; truth = (2+2=4); falsehood = (2 + 2 = 5); printf ("truth is Z4\n", truth); printf ("falsehood is d\n", falsehood) ; exit (0); + ‘You should receive the following result: truth is 1 falsehood is 0

You might also like