27
2 Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements. Use the fundamental data types. Use arithmetic operators. Learn the precedence of arithmetic operators. Write simple decision-making statements.

Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2Introduction to C Programming

O b j e c t i v e sIn this chapter you’ll:

� Write simple C programs.

� Use simple input and output statements.

� Use the fundamental data types.

� Use arithmetic operators.

� Learn the precedence of arithmetic operators.

� Write simple decision-making statements.

Page 2: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

20 Chapter 2 Introduction to C ProgrammingO

utl

ine

2.1 IntroductionThe C language facilitates a structured and disciplined approach to computer-programdesign. In this chapter we introduce C programming and present several examples thatillustrate many important features of C. In Chapters 3 and 4 we present an introductionto structured programming in C. We then use the structured approach throughout the re-mainder of the text.

2.2 A Simple C Program: Printing a Line of TextWe begin by considering a simple C program. Our first example prints a line of text. Theprogram and its screen output are shown in Fig. 2.1.

CommentsThis program illustrates several important C features. Lines 1 and 2

begin with //, indicating that these two lines are comments. Comments do not cause thecomputer to perform any action when the program is run. Comments are ignored by theC compiler and do not cause any machine-language object code to be generated. The pre-ceding comment simply describes the figure number, file name and purpose of the pro-gram.

You can also use /*…*/ multi-line comments in which everything from /* on thefirst line to */ at the end of the last line is a comment. We prefer // comments becausethey’re shorter and they eliminate common programming errors that occur with /*…*/

comments, especially when the closing */ is omitted.

2.1 Introduction2.2 A Simple C Program: Printing a Line

of Text2.3 Another Simple C Program: Adding

Two Integers

2.4 Arithmetic in C2.5 Decision Making: Equality and

Relational Operators2.6 Secure C Programming

1 // Fig. 2.1: fig02_01.c2 // A first program in C.3 #include <stdio.h>45 // function main begins program execution6 int main( void )7 {8 printf( "Welcome to C!\n" );9 } // end function main

Welcome to C!

Fig. 2.1 | A first program in C.

// Fig. 2.1: fig02_01.c// A first program in C

Page 3: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2.2 A Simple C Program: Printing a Line of Text 21

#include Preprocessor DirectiveLine 3

is a directive to the C preprocessor. Lines beginning with # are processed by the prepro-cessor before compilation. Line 3 tells the preprocessor to include the contents of the stan-dard input/output header (<stdio.h>) in the program. This header contains informationused by the compiler when compiling calls to standard input/output library functions suchas printf (line 8). We explain the contents of headers in more detail in Chapter 5.

Blank Lines and White SpaceLine 4 is simply a blank line. You use blank lines, space characters and tab characters (i.e.,“tabs”) to make programs easier to read. Together, these characters are known as whitespace. White-space characters are normally ignored by the compiler.

The main FunctionLine 6

is a part of every C program. The parentheses after main indicate that main is a function.C programs contain one or more functions, one of which must be main. Every program inC begins executing at the function main. Functions can return information. The keywordint to the left of main indicates that main “returns” an integer (whole-number) value.We’ll explain what this means when we demonstrate how to create your own functions inChapter 5. For now, simply include the keyword int to the left of main in each of yourprograms. Functions also can receive information when they’re called upon to execute. Thevoid in parentheses here means that main does not receive any information. In Chapter 14,we’ll show an example of main receiving information.

A left brace, {, begins the body of every function (line 7). A corresponding right braceends each function (line 9). This pair of braces and the portion of the program betweenthe braces is called a block. The block is an important program unit in C.

An Output StatementLine 8

instructs the computer to perform an action, namely to print on the screen the string ofcharacters marked by the quotation marks. A string is sometimes called a character string,a message or a literal. The entire line, including the printf function (the “f” stands for“formatted”), its argument within the parentheses and the semicolon (;), is called a state-ment. Every statement must end with a semicolon (also known as the statement termina-tor). When the preceding printf statement is executed, it prints the message Welcome to

C! on the screen. The characters normally print exactly as they appear between the doublequotes in the printf statement.

#include <stdio.h>

int main( void )

Good Programming Practice 2.1Every function should be preceded by a comment describing the purpose of the function.

printf( "Welcome to C!\n" );

Page 4: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

22 Chapter 2 Introduction to C Programming

Escape SequencesNotice that the characters \n were not printed on the screen. The backslash (\) is called anescape character. It indicates that printf is supposed to do something out of the ordinary.When encountering a backslash in a string, the compiler looks ahead at the next characterand combines it with the backslash to form an escape sequence. The escape sequence \n

means newline. When a newline appears in the string output by a printf, the newlinecauses the cursor to position to the beginning of the next line on the screen. Some com-mon escape sequences are listed in Fig. 2.2.

Because the backslash has special meaning in a string, i.e., the compiler recognizes itas an escape character, we use a double backslash (\\) to place a single backslash in a string.Printing a double quote also presents a problem because double quotes mark the bound-aries of a string—such quotes are not printed. By using the escape sequence \" in a stringto be output by printf, we indicate that printf should display a double quote. The rightbrace, }, (line 9) indicates that the end of main has been reached.

We said that printf causes the computer to perform an action. As any programexecutes, it performs a variety of actions and makes decisions. Section 2.5 discusses deci-sion making. Chapter 3 discusses this action/decision model of programming in depth.

The Linker and ExecutablesStandard library functions like printf and scanf are not part of the C programming lan-guage. For example, the compiler cannot find a spelling error in printf or scanf. Whenthe compiler compiles a printf statement, it merely provides space in the object programfor a “call” to the library function. But the compiler does not know where the library func-tions are—the linker does. When the linker runs, it locates the library functions and insertsthe proper calls to these library functions in the object program. Now the object programis complete and ready to be executed. For this reason, the linked program is called an ex-ecutable. If the function name is misspelled, the linker will spot the error, because it willnot be able to match the name in the C program with the name of any known function inthe libraries.

Escape sequence Description

\n Newline. Position the cursor at the beginning of the next line.

\t Horizontal tab. Move the cursor to the next tab stop.

\a Alert. Produces a sound or visible alert without changing the currentcursor position.

\\ Backslash. Insert a backslash character in a string.

\" Double quote. Insert a double-quote character in a string.

Fig. 2.2 | Some common escape sequences .

Good Programming Practice 2.2Add a comment to the line containing the right brace, }, that closes every function, in-cluding main.

Page 5: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2.2 A Simple C Program: Printing a Line of Text 23

Using Multiple printfsThe printf function can print Welcome to C! several different ways. For example, the pro-gram of Fig. 2.3 produces the same output as the program of Fig. 2.1. This works becauseeach printf resumes printing where the previous printf stopped printing. The firstprintf (line 8) prints Welcome followed by a space, and the second printf (line 9) beginsprinting on the same line immediately following the space.

One printf can print several lines by using additional newline characters as inFig. 2.4. Each time the \n (newline) escape sequence is encountered, output continues atthe beginning of the next line.

Good Programming Practice 2.3Indent the entire body of each function one level of indentation (we recommend threespaces) within the braces that define the body of the function. This indentation emphasizesthe functional structure of programs and helps make programs easier to read.

Good Programming Practice 2.4Set a convention for the size of indent you prefer and then uniformly apply that conven-tion. The tab key may be used to create indents, but tab stops may vary.

1 // Fig. 2.3: fig02_03.c2 // Printing on one line with two printf statements.3 #include <stdio.h>45 // function main begins program execution6 int main( void )7 {89

10 } // end function main

Welcome to C!

Fig. 2.3 | Printing on one line with two printf statements.

1 // Fig. 2.4: fig02_04.c2 // Printing multiple lines with a single printf.3 #include <stdio.h>45 // function main begins program execution6 int main( void )7 {8 printf( "Welcome to C!\n" );9 } // end function main

WelcometoC!

Fig. 2.4 | Printing multiple lines with a single printf.

printf( "Welcome " );printf( "to C!\n" );

\n \n

Page 6: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

24 Chapter 2 Introduction to C Programming

2.3 Another Simple C Program: Adding Two IntegersOur next program uses the Standard Library function scanf to obtain two integers typedby a user at the keyboard, computes the sum of these values and prints the result usingprintf. The program and sample output are shown in Fig. 2.5. [In the input/output dia-log of Fig. 2.5, we emphasize the numbers entered by the user in bold.]

The comment in line 2 states the purpose of the program. As we stated earlier, everyprogram begins execution with main. The left brace { (line 7) marks the beginning of thebody of main, and the corresponding right brace } (line 21) marks the end of main.

Variables and Variable DefinitionsLines 8–10

are definitions. The names integer1, integer2 and sum are the names of variables—lo-cations in memory where values can be stored for use by a program. These definitionsspecify that variables integer1, integer2 and sum are of type int, which means thatthey’ll hold integer values, i.e., whole numbers such as 7, –11, 0, 31914 and the like.

1 // Fig. 2.5: fig02_05.c2 // Addition program.3 #include <stdio.h>45 // function main begins program execution6 int main( void )7 {89

101112 printf( "Enter first integer\n" ); // prompt131415 printf( "Enter second integer\n" ); // prompt161718192021 } // end function main

Enter first integer45Enter second integer72Sum is 117

Fig. 2.5 | Addition program.

int integer1; // first number to be entered by userint integer2; // second number to be entered by userint sum; // variable in which sum will be stored

int integer1; // first number to be entered by userint integer2; // second number to be entered by userint sum; // variable in which sum will be stored

scanf( "%d", &integer1 ); // read an integer

scanf( "%d", &integer2 ); // read an integer

sum = integer1 + integer2; // assign total to sum

printf( "Sum is %d\n", sum ); // print sum

Page 7: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2.3 Another Simple C Program: Adding Two Integers 25

All variables must be defined with a name and a data type before they can be used ina program. For readers using the Microsoft Visual C++ compiler, note that we’re placingour variable definitions immediately after the left brace that begins the body of main. TheC standard allows you to place each variable definition anywhere in main before that vari-able’s first use in the code. Some compilers, such as GNU gcc, have implemented thiscapability. We’ll address this issue in more depth in later chapters.

The preceding definitions could have been combined into a single definition state-ment as follows:

but that would have made it difficult to describe the variables with corresponding com-ments as we did in lines 8–10.

Identifiers and Case SensitivityA variable name in C is any valid identifier. An identifier is a series of characters consistingof letters, digits and underscores (_) that does not begin with a digit. C is case sensitive—uppercase and lowercase letters are different in C, so a1 and A1 are different identifiers.

Syntax ErrorsWe discussed what syntax errors are in Chapter 1. Recall that the Microsoft Visual C++compiler requires variable definitions to be placed after the left brace of a function and be-fore any executable statements. Therefore, in the program in Fig. 2.5, inserting the defini-tion of integer1 after the first printf would cause a syntax error in Visual C++.

Prompting MessagesLine 12

displays the literal "Enter first integer" and positions the cursor to the beginning of thenext line. This message is called a prompt because it tells the user to take a specific action.

int integer1, integer2, sum;

Error-Prevention Tip 2.1Avoid starting identifiers with the underscore character (_) to prevent conflicts with com-piler-generated identifiers and standard library identifiers.

Good Programming Practice 2.5The first letter of an identifier used as a simple variable name should be a lowercase letter.Later in the text we’ll assign special significance to identifiers that use all capital letters.

Good Programming Practice 2.6Multiple-word variable names can help make a program more readable. Separate thewords with underscores as in total_commissions, or, if you run the words together, begineach word after the first with a capital letter as in totalCommissions. The latter style ispreferred.

Common Programming Error 2.1Placing variable definitions among executable statements causes syntax errors in the Mi-crosoft Visual C++ Compiler.

printf( "Enter first integer\n" ); // prompt

Page 8: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

26 Chapter 2 Introduction to C Programming

The scanf Function and Formatted InputsThe next statement

uses scanf (the “f” stands for “formatted”) to obtain a value from the user. The functionreads from the standard input, which is usually the keyboard. This scanf has two argu-ments, "%d" and &integer1. The first, the format control string, indicates the type of datathat should be entered by the user. The %d conversion specifier indicates that the datashould be an integer (the letter d stands for “decimal integer”). The % in this context istreated by scanf (and printf as we’ll see) as a special character that begins a conversionspecifier. The second argument of scanf begins with an ampersand (&)—called the ad-dress operator—followed by the variable name. The &, when combined with the variablename, tells scanf the location (or address) in memory at which the variable integer1 isstored. The computer then stores the value that the user enters for integer1 at that loca-tion. The use of ampersand (&) is often confusing to novice programmers or to people whohave programmed in other languages that do not require this notation. For now, just re-member to precede each variable in every call to scanf with an ampersand. Some excep-tions to this rule are discussed in Chapters 6 and 7. The use of the ampersand will becomeclear after we study pointers in Chapter 7.

When the computer executes the preceding scanf, it waits for the user to enter a valuefor variable integer1. The user responds by typing an integer, then pressing the Enter keyto send the number to the computer. The computer then assigns this number, or value, tothe variable integer1. Any subsequent references to integer1 in this program will use thissame value. Functions printf and scanf facilitate interaction between the user and thecomputer. Because this interaction resembles a dialogue, it’s often called interactive com-puting.

Line 15

displays the message Enter second integer on the screen, then positions the cursor to thebeginning of the next line. This printf also prompts the user to take action.

Line 16

obtains a value for variable integer2 from the user.

Assignment StatementThe assignment statement in line 18

calculates the total of variables integer1 and integer2 and assigns the result to variablesum using the assignment operator =. The statement is read as, “sum gets the value ofinteger1 + integer2.” Most calculations are performed in assignments. The = operator

scanf( "%d", &integer1 ); // read an integer

Good Programming Practice 2.7Place a space after each comma (,) to make programs more readable.

printf( "Enter second integer\n" ); // prompt

scanf( "%d", &integer2 ); // read an integer

sum = integer1 + integer2; // assign total to sum

Page 9: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2.4 Arithmetic in C 27

and the + operator are called binary operators because each has two operands. The + oper-ator’s two operands are integer1 and integer2. The = operator’s two operands are sumand the value of the expression integer1 + integer2.

Printing with a Format Control StringLine 20

calls function printf to print the literal Sum is followed by the numerical value of variablesum on the screen. This printf has two arguments, "Sum is %d\n" and sum. The first ar-gument is the format control string. It contains some literal characters to be displayed, andit contains the conversion specifier %d indicating that an integer will be printed. The sec-ond argument specifies the value to be printed. Notice that the conversion specifier for aninteger is the same in both printf and scanf—this is the case for most C data types.

Calculations in printf StatementsCalculations can also be performed inside printf statements. We could have combinedthe previous two statements into the statement

The right brace, }, at line 21 indicates that the end of function main has been reached.

2.4 Arithmetic in CMost C programs perform calculations using the C arithmetic operators (Fig. 2.6). Theasterisk (*) indicates multiplication and the percent sign (%) denotes the remainder opera-tor, which is introduced below. In algebra, to multiply a times b, we simply place thesesingle-letter variable names side by side, as in ab. In C, however, if we were to do this, abwould be interpreted as a single, two-letter name (or identifier). Therefore, multiplicationmust be explicitly denoted by using the * operator, as in a * b. The arithmetic operatorsare all binary operators. For example, the expression 3 + 7 contains the binary operator +and the operands 3 and 7.

Good Programming Practice 2.8Place spaces on either side of a binary operator for readability.

printf( "Sum is %d\n", sum ); // print sum

printf( "Sum is %d\n", integer1 + integer2 );

Common Programming Error 2.2Forgetting to precede a variable in a scanf statement with an ampersand when that vari-able should, in fact, be preceded by an ampersand results in an execution-time error. Onmany systems, this causes a “segmentation fault” or “access violation.” Such an error occurswhen a user’s program attempts to access a part of the computer’s memory to which it doesnot have access privileges. The precise cause of this error will be explained in Chapter 7.

Common Programming Error 2.3Preceding a variable included in a printf statement with an ampersand when, in fact,that variable should not be preceded by an ampersand.

Page 10: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

28 Chapter 2 Introduction to C Programming

Integer Division and the Remainder OperatorInteger division yields an integer result. For example, the expression 7 / 4 evaluates to 1and the expression 17 / 5 evaluates to 3. C provides the remainder operator, %, whichyields the remainder after integer division. The remainder operator is an integer operatorthat can be used only with integer operands. The expression x % y yields the remainder af-ter x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. We’ll discuss many interestingapplications of the remainder operator.

Arithmetic Expressions in Straight-Line FormArithmetic expressions in C must be written in straight-line form to facilitate enteringprograms into the computer. Thus, expressions such as “a divided by b” must be writtenas a/b so that all operators and operands appear in a straight line. The algebraic notation

is generally not acceptable to compilers, although some special-purpose software packagesdo support more natural notation for complex mathematical expressions.

Parentheses for Grouping SubexpressionsParentheses are used in C expressions in the same manner as in algebraic expressions. Forexample, to multiply a times the quantity b + c we write a * ( b + c ).

Rules of Operator PrecedenceC applies the operators in arithmetic expressions in a precise sequence determined by thefollowing rules of operator precedence, which are generally the same as those in algebra:

1. Operators in expressions contained within pairs of parentheses are evaluated first.Parentheses are said to be at the “highest level of precedence.” In cases of nested,or embedded, parentheses, such as

the operators in the innermost pair of parentheses are applied first.

C operation Arithmetic operator Algebraic expression C expression

Addition + f + 7 f + 7

Subtraction – p – c p - c

Multiplication * bm b * m

Division / x / y or or x ÷ y x / y

Remainder % r mod s r % s

Fig. 2.6 | Arithmetic operators.

Common Programming Error 2.4An attempt to divide by zero is normally undefined on computer systems and generally re-sults in a fatal error, i.e., an error that causes the program to terminate immediately with-out having successfully performed its job. Nonfatal errors allow programs to run tocompletion, often producing incorrect results.

( ( a + b ) + c )

xy--

ab--

Page 11: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2.4 Arithmetic in C 29

2. Multiplication, division and remainder operations are applied next. If an ex-pression contains several multiplication, division and remainder operations, eval-uation proceeds from left to right. Multiplication, division and remainder are saidto be on the same level of precedence.

3. Addition and subtraction operations are evaluated next. If an expression containsseveral addition and subtraction operations, evaluation proceeds from left to right.Addition and subtraction also have the same level of precedence, which is lowerthan the precedence of the multiplication, division and remainder operations.

4. The assignment operator (=) is evaluated last.

The rules of operator precedence specify the order C uses to evaluate expressions.1

When we say evaluation proceeds from left to right, we’re referring to the associativity ofthe operators. We’ll see that some operators associate from right to left. Figure 2.7 sum-marizes these rules of operator precedence for the operators we’ve seen so far.

Sample Algebraic and C ExpressionsNow let’s consider several expressions in light of the rules of operator precedence. Eachexample lists an algebraic expression and its C equivalent. The following expression calcu-lates the arithmetic mean (average) of five terms.

The parentheses are required to group the additions because division has higher prece-dence than addition. The entire quantity ( a + b + c + d + e ) should be divided by 5. Ifthe parentheses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluatesincorrectly as

1. We use simple examples to explain the order of evaluation of expressions. Subtle issues occur in morecomplex expressions that you’ll encounter later in the book. We’ll discuss these issues as they arise.

Operator(s) Operation(s) Order of evaluation (precedence)

( ) Parentheses Evaluated first. If the parentheses are nested, the expres-sion in the innermost pair is evaluated first. If there areseveral pairs of parentheses “on the same level” (i.e., notnested), they’re evaluated left to right.

*/%

MultiplicationDivisionRemainder

Evaluated second. If there are several, they’re evaluatedleft to right.

+-

AdditionSubtraction

Evaluated third. If there are several, they’re evaluated leftto right.

= Assignment Evaluated last.

Fig. 2.7 | Precedence of arithmetic operators.

Algebra:

C: m = ( a + b + c + d + e ) / 5;

ma b c d e+ + + +

5-------------------------------------=

a b c de5---+ + + +

Page 12: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

30 Chapter 2 Introduction to C Programming

The following expression is the equation of a straight line:

No parentheses are required. The multiplication is evaluated first because multiplicationhas a higher precedence than addition.

The following expression contains remainder (%), multiplication, division, addition,subtraction and assignment operations:

The circled numbers indicate the order in which C evaluates the operators. The multipli-cation, remainder and division are evaluated first in left-to-right order (i.e., they associatefrom left to right) because they have higher precedence than addition and subtraction. Theaddition and subtraction are evaluated next. They’re also evaluated left to right. Finally,the result is assigned to the variable z.

Not all expressions with several pairs of parentheses contain nested parentheses. Forexample, the following expression does not contain nested parentheses—instead, theparentheses are said to be “on the same level.”

Evaluation of a Second-Degree PolynomialTo develop a better understanding of the rules of operator precedence, let’s see how C eval-uates a second-degree polynomial.

The circled numbers under the statement indicate the order in which C performs the oper-ations. There’s no arithmetic operator for exponentiation in C, so we’ve represented x2 asx * x. The C Standard Library includes the pow (“power”) function to perform expo-nentiation. Because of some subtle issues related to the data types required by pow, we defera detailed explanation of pow until Chapter 4.

Suppose variables a, b, c and x in the preceding second-degree polynomial are initial-ized as follows: a = 2, b = 3, c = 7 and x = 5. Figure 2.8 illustrates the order in which theoperators are applied.

As in algebra, it’s acceptable to place unnecessary parentheses in an expression to makethe expression clearer. These are called redundant parentheses. For example, the pre-ceding statement could be parenthesized as follows:

Algebra: y = mx + b

C: y = m * x + b;

a * ( b + c ) + c * ( d + e )

y = ( a * x * x ) + ( b * x ) + c;

z

6 1 2 4 3 5

= p * r % q + w / x - y;

z = pr%q + w/x – yAlgebra:C:

6 1 2 4 3 5

y = a * x * x + b * x + c;

Page 13: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2.5 Decision Making: Equality and Relational Operators 31

2.5 Decision Making: Equality and Relational OperatorsExecutable statements either perform actions (such as calculations or input or output ofdata) or make decisions (we’ll soon see several examples of these). We might make a deci-sion in a program, for example, to determine whether a person’s grade on an exam is great-er than or equal to 60 and whether the program should print the message“Congratulations! You passed.” This section introduces a simple version of C’s if state-ment that allows a program to make a decision based on the truth or falsity of a statementof fact called a condition. If the condition is true (i.e., the condition is met), the statementin the body of the if statement is executed. If the condition is false (i.e., the conditionisn’t met), the body statement isn’t executed. Whether the body statement is executed ornot, after the if statement completes, execution proceeds with the next statement after theif statement.

Conditions in if statements are formed by using the equality operators and relationaloperators summarized in Fig. 2.9. The relational operators all have the same level of prece-dence and they associate left to right. The equality operators have a lower level of prece-dence than the relational operators and they also associate left to right. [Note: In C, acondition may actually be any expression that generates a zero (false) or nonzero (true) value.]

Fig. 2.8 | Order in which a second-degree polynomial is evaluated.

Common Programming Error 2.5Confusing the equality operator == with the assignment operator. To avoid this confusion,the equality operator should be read “double equals” and the assignment operator shouldbe read “gets” or “is assigned the value of.” As you’ll see, confusing these operators may notcause an easy-to-recognize compilation error, but may cause extremely subtle logic errors.

(Leftmost multiplication)

(Leftmost multiplication)

(Multiplication before addition)

(Leftmost addition)

(Last addition)

(Last operation—place 72 in y)

Step 1. y = 2 * 5 * 5 + 3 * 5 + 7;

2 * 5 is 10

Step 2. y = 10 * 5 + 3 * 5 + 7;

10 * 5 is 50

Step 3. y = 50 + 3 * 5 + 7;

3 * 5 is 15

Step 4. y = 50 + 15 + 7;

50 + 15 is 65

Step 5. y = 65 + 7;

65 + 7 is 72

Step 6. y = 72

Page 14: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

32 Chapter 2 Introduction to C Programming

Figure 2.10 uses six if statements to compare two numbers entered by the user. If thecondition in any of these if statements is true, the printf statement associated with thatif executes. The program and three sample execution outputs are shown in the figure.

Algebraic equality orrelational operator

C equality orrelationaloperator

Exampleof Ccondition Meaning of C condition

Equality operators

= == x == y x is equal to y

≠ != x != y x is not equal to y

Relational operators

> > x > y x is greater than y

< < x < y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y

Fig. 2.9 | Equality and relational operators.

1 // Fig. 2.10: fig02_10.c2 // Using if statements, relational3 // operators, and equality operators.4 #include <stdio.h>56 // function main begins program execution7 int main( void )8 {9 int num1; // first number to be read from user

10 int num2; // second number to be read from user1112 printf( "Enter two integers, and I will tell you\n" );13 printf( "the relationships they satisfy: " );1415 scanf( "%d%d", &num1, &num2 ); // read two integers161718192021 if ( ) {22 printf( "%d is not equal to %d\n", num1, num2 );23 } // end if2425 if ( ) {26 printf( "%d is less than %d\n", num1, num2 );27 } // end if

Fig. 2.10 | Using if statements, relational operators, and equality operators. (Part 1 of 2.)

if ( num1 == num2 ) {printf( "%d is equal to %d\n", num1, num2 );

} // end if

num1 != num2

num1 < num2

Page 15: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2.5 Decision Making: Equality and Relational Operators 33

The program uses scanf (line 15) to input two numbers. Each conversion specifierhas a corresponding argument in which a value will be stored. The first %d converts a valueto be stored in the variable num1, and the second %d converts a value to be stored in thevariable num2.

2829 if ( ) {30 printf( "%d is greater than %d\n", num1, num2 );31 } // end if3233 if ( ) {34 printf( "%d is less than or equal to %d\n", num1, num2 );35 } // end if3637 if ( ) {38 printf( "%d is greater than or equal to %d\n", num1, num2 );39 } // end if40 } // end function main

Enter two integers, and I will tell youthe relationships they satisfy: 3 73 is not equal to 73 is less than 73 is less than or equal to 7

Enter two integers, and I will tell youthe relationships they satisfy: 22 1222 is not equal to 1222 is greater than 1222 is greater than or equal to 12

Enter two integers, and I will tell youthe relationships they satisfy: 7 7

7 is equal to 77 is less than or equal to 77 is greater than or equal to 7

Good Programming Practice 2.9Although it’s allowed, there should be no more than one statement per line in a program.

Common Programming Error 2.6Placing commas (when none are needed) between conversion specifiers in the format con-trol string of a scanf statement.

Fig. 2.10 | Using if statements, relational operators, and equality operators. (Part 2 of 2.)

num1 > num2

num1 <= num2

num1 >= num2

Page 16: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

34 Chapter 2 Introduction to C Programming

Comparing NumbersThe if statement in lines 17–19

compares the values of variables num1 and num2 to test for equality. If the values are equal,the statement in line 18 displays a line of text indicating that the numbers are equal. If theconditions are true in one or more of the if statements starting in lines 21, 25, 29, 33and 37, the corresponding body statement displays an appropriate line of text. Indentingthe body of each if statement and placing blank lines above and below each if statementenhances program readability.

A left brace, {, begins the body of each if statement (e.g., line 17). A correspondingright brace, }, ends each if statement’s body (e.g., line 19). Any number of statements canbe placed in the body of an if statement.2

Figure 2.11 lists from highest to lowest the precedence of the operators introduced inthis chapter. Operators are shown top to bottom in decreasing order of precedence. Theequals sign is also an operator. All these operators, with the exception of the assignmentoperator =, associate from left to right. The assignment operator (=) associates from rightto left.

Some of the words we’ve used in the C programs in this chapter—in particular intand if—are keywords or reserved words of the language. Figure 2.12 contains the C key-words. These words have special meaning to the C compiler, so you must be careful notto use these as identifiers such as variable names.

if ( num1 == num2 ) {printf( "%d is equal to %d\n", num1, num2 );

}

Common Programming Error 2.7Placing a semicolon immediately to the right of the right parenthesis after the conditionin an if statement.

Good Programming Practice 2.10A lengthy statement may be spread over several lines. If a statement must be split acrosslines, choose breaking points that make sense (such as after a comma in a comma-separatedlist). If a statement is split across two or more lines, indent all subsequent lines. It’s notcorrect to split identifiers.

2. Using braces to delimit the body of an if statement is optional when the body contains only onestatement. Many programmers consider it good practice to always use these braces. In Chapter 3,we’ll explain the issues.

Good Programming Practice 2.11Refer to the operator precedence chart when writing expressions containing many opera-tors. Confirm that the operators in the expression are applied in the proper order. If you’reuncertain about the order of evaluation in a complex expression, use parentheses to groupexpressions or break the statement into several simpler statements. Be sure to observe thatsome of C’s operators such as the assignment operator (=) associate from right to left ratherthan from left to right.

Page 17: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

2.6 Secure C Programming 35

2.6 Secure C ProgrammingWe mentioned The CERT C Secure Coding Standard in the Preface and indicated that wewould follow certain guidelines that will help you avoid programming practices that opensystems to attacks.

Avoid Single-Argument printfsOne such guideline is to avoid using printf with a single string argument. If you need todisplay a string that terminates with a newline, use the puts function, which displays itsstring argument followed by a newline character. For example, in Fig. 2.1, line 8

should be written as:

Operators Associativity

() left to right

* / % left to right

+ - left to right

< <= > >= left to right

== != left to right

= right to left

Fig. 2.11 | Precedence and associativity of theoperators discussed so far.

Keywords

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

Keywords added in C99 standard

_Bool _Complex _Imaginary inline restrict

Keywords added in C11 standard

_Alignas _Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local

Fig. 2.12 | C’s keywords.

printf( "Welcome to C!\n" );

puts( "Welcome to C!" );

Page 18: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

36 Chapter 2 Introduction to C Programming

We did not include \n in the preceding string because puts adds it automatically.If you need to display a string without a terminating newline character, use printf

with two arguments—a "%s" format control string and the string to display. The %s con-version specifier is for displaying a string. For example, in Fig. 2.3, line 8

should be written as:

Although the printfs in this chapter as written are actually not insecure, these changesare responsible coding practices that will eliminate certain security vulnerabilities as we getdeeper into C—we’ll explain the rationale later in the book. From this point forward, weuse these practices in the chapter examples and you should use them in your own code.

For more information on this issue, see CERT C Secure Coding rule FIO30-C

In Chapter 6’s Secure C Programming section, we’ll explain the notion of user input asreferred to by this CERT guideline.

scanf and printf, scanf_s and printf_s

We introduced scanf and printf in this chapter. We’ll be saying more about these in sub-sequent Secure C Coding Guidelines sections. We’ll also discuss scanf_s and printf_s,which were introduced in C11.

printf( "Welcome " );

printf( "%s", "Welcome " );

www.securecoding.cert.org/confluence/display/seccode/FIO30-C.+Exclude+user+input+from+format+strings

Page 19: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

Symbols\t horizontal-tab escape sequence 22^ bitwise exclusive OR operator 271^ inverted scan set 254^= bitwise exclusive OR assignment oper-

ator 278__func__ predefined identifier 411__VA_ARGS__ 408_Pragma operator 407, (comma operator) 62, 65!, logical negation (NOT) operator 77,

78!= inequality operator 32? 41?: conditional operator 41, 54, 119. dot operator 262. structure member operator 263" 250* assignment suppression character 256* multiplication operator 27, 48*= multiplication assignment operator 54/ division operator 48/*…*/ multi-line comment 20/= division assignment operator 54\\ backslash-character escape sequence

22\? escape sequence 250\' single-quote-character escape sequence

250\" double-quote-character escape se-

quence 250\\ backslash-character escape sequence

250\0 null character escape sequence 133\a alert escape sequence 22, 250\b escape sequence 250\f escape sequence 209\f form-feed escape sequence 250\n escape sequence 209\n newline escape sequence 22, 251\r carriage-return escape sequence 251\r escape sequence 209\t escape sequence 209\t horizontal-tab escape sequence 251\v escape sequence 209, 251& address operator 26& and * pointer operators 171& bitwise AND operator 271&& operator 77, 119&&, logical AND operator 77&= bitwise AND assignment operator 278# flag 249# preprocessor operator 21, 348## preprocessor operator 348% character in a conversion specifier 48,

239

% remainder operator 27, 99%% conversion specifier 244%= remainder assignment operator 54%c conversion specifier 93, 244, 254%d conversion specifier 93%E conversion specifier 242, 253%e conversion specifier 242, 253%f conversion specifier 48, 93%g conversion specifier 253%hd conversion specifier 93%hu conversion specifier 93%i conversion specifier 252%ld conversion specifier 93%Lf conversion specifier 93%lf conversion specifier 93%lld conversion specifier 93%llu conversion specifier 93%lu conversion specifier 93%p conversion specifier 170, 244%s conversion specifier 36, 196, 244, 254%u conversion specifier 50, 93, 240%X conversion specifier 252+ flag 248+ flag 247- minus operator 54+ unary plus operator 54-- operator 52, 54, 189++ operator 52, 54, 189+= addition assignment operator 52, 54< less than operator 32< redirect input symbol 352<< left-shift operator 271<<= left-shift assignment operator 278= assignment operator 54-= subtraction assignment operator 54== equality operator 81> greater than operator 32> redirect output symbol 353-> structure pointer operator 262>> append output symbol 353>> right-shift operator 271>>= right shift assignment operator 278| bitwise inclusive OR operator 271| pipe 352|= bitwise inclusive OR assignment oper-

ator 278|| 119||, logical OR operator 77~ bitwise one’s complement 271~, bitwise complement operator 276

Numerics0 Conversion specifier 26, 252, 2530x 249

Aa file open mode 291a.out 7a+ file open mode 291ab file open mode 291ab+ file open mode 291abnormal program termination 360abort function 349absolute-value 86abstraction 87access privileges 177access violation 27, 208, 244action 21, 22, 31, 43action symbol 39action/decision model 22actions 31active window 429add an integer to a pointer 188addition assignment operator (+=) 51address 320address of a bit field 282address operator (&) 26, 99, 134, 169,

172, 182aggregate data types 180aggregates 259alert (\a) 22algorithm

insertion sort 384merge sort 387selection sort 380

aligning 239American National Standards Committee

on Computers and Information Pro-cessing 3

American National Standards Institute(ANSI) 3, 3

ampersand (&) 26, 27AND 270Android 18

operating system 16, 18smartphone 18

Annex K 165, 166ANSI 3Apache Software Foundation 17append output symbol >> 353Apple Inc. 17Apple Macintosh 18argc 355argument 21argument (of a function) 85arguments 344argv 355arithmetic assignment operators 52

+=, -=, *=, /=, and %= 52arithmetic conversion rules 92arithmetic expressions 188

Index

Page 20: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

450 Index

arithmetic mean 29arithmetic operators 27arithmetic overflow 55array 123, 124

bounds checking 165array bounds checking 131array initializer 126array initializer list 127array notation 193array of pointers 194, 202array of strings 194array subscript notation 134, 181, 194arrow operator (->) 262ASCII (American Standard Code for In-

formation Interchange) 70assert macro 349<assert.h> 97, 349Assigning elements of an array in C89 398assignment expressions 188assignment operator (=) 31assignment operators

=, +=, -=, *=, /=, and %= 52assignment statement 26associate from right to left 34, 48associativity 29, 35, 54, 124, 170, 278asterisk (*) 27atexit function 358audible (bell) 250auto 108auto storage class specifier 108automatic array 127automatic storage 108, 123automatic storage duration 108, 136automatic variable 108, 109Autos window 434

displaying state of objects 435Autos window displaying the state of lo-

calTime 435average 29

BB 2backslash (\) 22, 250, 346bank account program 304bar chart 131base 369base 10 number system 215base 16 number system 215base 8 number system 215base case(s) 113BCPL 2Bell Laboratories 2, 4Big O notation 379, 383binary 209binary (base 2) number system 369binary arithmetic operators 48binary operator 27binary search 149, 151, 152binary search tree 335, 339, 340binary tree 335binary tree sort 339bit field 279, 280bit field member name 279bit manipulation 282bitwise AND (&) operator 270, 275bitwise AND, bitwise inclusive OR, bit-

wise exclusive OR and bitwise comple-ment operators 273

bitwise assignment operators 278bitwise complement operator (~) 273,

276, 376bitwise data manipulations 270bitwise exclusive OR (^) operator 270,

276bitwise inclusive OR (|) operator 270,

276bitwise operators 270bitwise shift operators 277bitwise XOR 270BlackBerry OS 16blank 40block 43, 89block of data 231block scope 109body of a function 21, 34body of a while 44Bohm, C. 38_Bool 401_Bool Data Type 79boolean type 79, 401bounds checking 131, 165braces ({}) 43break 71, 75, 76break debugger command 439break mode 428, 439breakpoint 426, 437

inserting 439, 442yellow arrow in break mode 429

breakpointsinserting 428, 430red circle 428

bubble sort 142, 182, 184, 199bubble sort 149bubble sort with pass by reference 182buffer overflow 165building block approach 4byte 270

CC compiler 20C development environment 6C Environment 5C language 2C preprocessor 7, 21, 343C program and sample execution for the

class average problem with counter-controlled repetition 45

C program and sample execution for theclass average problem with sentinel-controlled repetition 46

C program and sample executions for ex-amination results problem 50

C standard document (INCITS/ISO/IEC9899-1999) 3

C Standard Library 4, 5C standard library 84, 99, 177C Standard Library documentation 4C# programming language 5C++ 91C11 395C11 headers 412C95 396C95 headers 396C99 3, 395, 411C99 headers 396calculations 26

call a function 84, 85, 88call-by-reference 264call-by-value 264caller 85calling function 85calloc 362Card dealing program 196card shuffling and dealing simulation

195, 196, 265caret (^) 255carriage return (’\r’) 209carry bit 376case label 71, 72, 109case sensitive 25casino 104cast 346cast operator 48, 93

(float) 48cbrt function 86ceil function 86char 69char 93, 207char * 244char ** 214char primitive type 69CHAR_BIT symbolic constant 273character array 133, 135character constant 178, 206, 244character handling library 208character handling library functions 208character set 70, 206character string 21, 125child 335class averaging problem 44clock 102coercion of arguments 92column 155comma operator (,) 62, 65, 119comma-separated list 62command-line arguments 355, 356comment 20Common Programming Errors overview

xviiCommunications of the ACM 38comparing strings 221comparison expressions 188compilation 7compilation error 7, 80compile 7compile phase 5compile-time error 7compiler 7, 20, 21, 22complement operator (~) 270complete algorithm 39_Complex 404complex 404complex number 403complex.h 404components (software) 5compound interest 65, 66compound literal 400compound statement 43computing the sum of the elements of an

array 129concatenating strings 221condition 31, 77conditional compilation 343, 346conditional execution of preprocessor di-

rectives 343

Page 21: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

Index 451

conditional expression 41conditional operator (?:) 41, 54connector symbols 39conserve storage 279const 177, 180, 184, 194const keyword 139const qualifier 176const type qualifier 141constant integral expression 73constant pointer 180, 181, 190constant pointer to constant data 177,

181constant pointer to non-constant data

177, 180, 181constant run time 379constant string 194continue 75, 76Continue command (debugger) 429continue debugger command 440control characters 212control-statement nesting 40control-statement stacking 40control structures 38control variable 58, 64

increment 59initial value 59name 59

controlling expression in a switch 71conversion 374conversion rules 92conversion specifications 239conversion specifier 26, 239

c 243e and E 241f 241for scanf 251g (or G) 242s 243

conversion specifiers%u 50

converson specifiers%s 36

converta binary number to decimal 374a hexadecimal number to decimal

374an octal number to decimal 374lowercase letters to uppercase letters

97copy 98copying strings 221cos function 86cosine 86counter 45counter-controlled loop 50counter-controlled repetition 45, 59, 60counting letter grades 71counting loop 60CPU 7craps (casino game) 104Creating and traversing a binary tree 336<Ctrl> c 360<ctype.h> header file 208, 97, 346Cube a variable using pass by reference

173Cube a variable using pass by value 172cube root function 86custom header 97Cygwin 396

Ddata structure 312date 98__DATE__, predefined symbolic constant

349deallocate memory 313debug 38debugger 347, 439

Autos window displaying state of ob-jects 435

break command 439break mode 428, 429, 439breakpoint 426, 437Continue command 429, 429continue command 440convenience variable (GNU debug-

ger) 440defined 437delete command 441finish command 445-g compiler option 438gdb command 438help command 439info break command 441inserting a breakpoint 428inserting breakpoints 439Locals window (Visual Studio de-

bugger) 430, 431logic error 437margin indicator bar 428next command 446print command 440quit command 441run command 438set command 442, 443Solution Configurations combobox

427step command 444Step Into command 432Step Out command 434Step Over command 433suspending program execution 430,

442watch command 446Watch window (Visual Studio) 430,

431decimal 209, 215decimal (base 10) number system 369decision 22, 22, 31, 31, 44decision symbol 39deck of cards 194, 195Declaring a variable in a for statement

header in C99 397decomposition 87decrement 59, 63, 189decrement a pointer 188decrement operator (--) 52default case 71, 72, 73default precision 48, 242#define 344#define preprocessor directive 128, 344defining occurrence 8definite repetition 58definition 24, 25delete debugger command 441deleting a node from a list 322delimiting characters 230dequeue 329dereferencing a pointer 170

dereferencing a void * pointer 190dereferencing operator (*) 170, 263derived data type 259designated initializer 398, 400determining the length of strings 221devices 7, 8diagnostics 97diamond symbol 39dice game 104dice rolling 104dice-rolling program 132Dice-rolling program using arrays instead

of switch 132digit 369directly reference a value 168disk 7displacement 300display 8Displaying an unsigned integer in bits

271Displaying the value of a union in both

member data types 269divide and conquer 84, 87division 28division by zero 360do...while repetition statement 39do…while statement example 73, 74document a program 20dot operator (.) 262double 92double backslash (\\) 22double complex 404double indirection (pointer to a pointer)

320double primitive type 66double quote character (") 22double quotes 244double-selection statement 39double-subscripted array 155, 158double-subscripted array representation

of a deck of cards 195double-subscripted array 195dummy value 46duplicate elimination 340duration 108, 110dynamic array 362dynamic data structure 168, 312dynamic memory allocation 313, 362dynamic memory management 168

EEclipse 6Eclipse Foundation 17edit phase 5editor 7, 206editor program 6efficiency of

insertion sort 387merge sort 392selection sort 383

element of an array 123elements 123#elif 346ellipsis (...) in a function prototype 353emacs 6embedded parentheses 28embedded system 3, 17empty statement 43

Page 22: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

452 Index

“end of data entry” 46end-of-file 70end-of-file marker 286, 289#endif 346end-of-file indicator 208, 217end-of-file key combination 352enqueue 329Enter key 72enter key 7, 26enum 107, 282enumeration 107, 283enumeration constant 107, 282, 346enumeration example 283environment 5EOF 70, 208equality and relational operators 190equality operator 31e-reader device 18<errno.h> 98#error 347error checking (in file processing) 302error conditions 98error message 8#error preprocessor directive 347escape character 22, 250escape sequence 22, 250event 360ex 86exclusive write mode 291executable image 7executable program 22execute 7execute phase 5executes 7exit and atexit functions 358exit function 358EXIT_FAILURE 358EXIT_SUCCESS 358exp function 86expand a macro 344explicit conversion 48exponential complexity 119exponential format 239exponential function 86exponential notation 241, 242exponentiation 30exponentiation operator 66expression 67, 90extern 108, 357external linkage 357external variable 109

Ff or F for a float 360fabs function 86Facebook 5, 17factorial function 113false 31FCB 286, 288fclose function 289fenv.h 396feof function 289, 302fgetc function 286fgets function 217, 287Fibonacci function 119Fibonacci series 116field width 67, 239, 245, 247, 256FIFO (first-in first-out) 329

FILE 286file 286file control block (FCB) 286, 288file descriptor 286file name 7file offset 293file open mode 288, 291FILE pointer 292file position pointer 293, 301__FILE__, predefined symbolic constant

349file processing

error checking 302file scope 109FILE structure 286final value 59final value of a control variable 62, 64finish debugger command 445first-in first-out (FIFO) 329flag value 46flags 239, 247, 249flexible array member 410(float) 48float 46, 48, 93<float.h> 98floating point 242floating-point conversion specifiers 242,

246, 252floating-point exception 360floating-point number 46, 49floating-point size limits 98floating-point suffix

f or F for a float 360l or L for a long double 360

floor function 86flowchart 39, 40flowcharting C’s sequence structure 39flowcharting double-selection if/else

statement 41flowcharting the do...while repetition

statement 75flowcharting the single-selection if state-

ment 40flowcharting the while repetition state-

ment 44flowline 38fmod function 86fopen function 291for header components 61for repetition statement 39, 64format control string 26, 239, 240, 246,

251formatted input/output model 296form-feed character (\f) 209fprintf function 287fprintf_s function 309fputc function 287fputs function 287fread function 287, 297free function 313, 328front of a queue 312fscanf function 287fseek function 299function 4, 7, 21, 84

argument 85body 89call 85, 89call and return 98caller 85

function (cont.)header 88, 89, 184, 201invoke 85, 88name 88, 108, 120, 199parameter 88, 174, 176, 180pointer 199, 202prototype 67, 88, 89, 91, 109, 174,

184prototype scope 109, 110return from 85, 85scope 109

function callstack 94, 180

fwrite 287, 297, 299

G-g command-line compiler option 438game of craps 104game playing 99gcc compilation command 7gdb command 438general utilities library (stdlib) 213generic pointer 190getc 346getchar 219, 219, 286, 346global variable 108, 109, 185, 268, 356golden mean 116golden ratio 116Good Programming Practices overview

xviigoto elimination 38goto-less programming 38goto statement 38, 109, 363Graphical User Interface (GUI) 18GUI (Grahical User Interface) 18

Hhard disk 7hardcopy printer 8hardware independent 2hardware platform 3head of a queue 312, 329header file

complex.h 404fenv.h 396inttypes.h 396iso646.h 396stdbool.h 401stdint.h 396tgmath.h 396wchar.h 396wctype.h 396

headers 21, 97, 34379<ctype.h> 208<stdio.h> 217<stdlib.h> 213<string.h> 221

help debugger command 439hexadecimal 209, 215, 239, 244hexadecimal (base 16) number system

369hexadecimal integer 170hierarchical boss function/worker func-

tion relationship 85highest level of precedence 28

Page 23: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

Index 453

High-performance card shuffling anddealing simulation 265

histogram 131Histogram printing 131horizontal tab (\t) 22, 209

Iidentifier(s) 25, 344#if 346if selection statement 31, 40, 43if...else selection statement 39, 40#ifdef preprocessor directive 346#ifndef preprocessor directive 346illegal instruction 360image 7implicit conversion 48INCITS/ISO/IEC 9899-1999 (C stan-

dard document) 3#include preprocessor directive 128,

343including headers 98increment 63increment a control variable 59, 62, 64increment a pointer 188increment operator (++) 52incremented 189indefinite postponement 196indefinite repetition 58indent 23indentation 40, 42indirection 168, 172indirection operator (*) 99, 170, 172indirectly reference a value 168infinite loop 48, 62infinite recursion 116info break debugger command 441information hiding 109, 182initial value of a control variable 59, 64initializer list 134Initializing multidimensional arrays 156initializing structures 262Initializing the elements of an array to ze-

ros 125Initializing the elements of an array with

an initializer list 126inline function 410inner block 110innermost pair of parentheses 28inorder 336inOrder traversal 339Inputting data with a field width 256inserting a breakpoint 428inserting literal characters 239insertion sort algorithm 384, 385, 387instruction 7int type 21, 24, 93integer 21, 24integer array 123integer constant 181integer conversion specifiers 240integer division 28, 48integer promotion 92integer suffix

l or L for a long int 359ll or LL for a long long int 359u or U for an unsigned int 359

integral size limits 98interactive attention signal 360

interactive computing 26Interface Builder 18internal linkage 357International Standards Organization

(ISO) 3interrupt 360inttypes.h 396inverted scan set 255invoke a function 85, 88iOS 16iPod Touch 18isalnum function 208, 209isalpha function 208, 209isblank function 208iscntrl function 209, 212isdigit function 208, 209isgraph function 209, 212islower function 209, 211ISO 3iso646.h header file 396isprint function 209, 212ispunct function 209, 212isspace function 209, 212isupper function 211isxdigit function 209,iteration 120iteration statement 43iterative function 151

JJacopini, G. 38Java programming language 5, 18JavaScript 5Jobs, Steve 17

Kkernel 16Kernighan, B. W. 2key value 149keyboard 24, 26, 217Keywords

_Bool 401_Complex 404inline 410restrict 409

keywords 34added in C11 35added in C99 35

Ll or L for a long double 360l or L for a long int 359label 109, 363last-in, first-out (LIFO) 94, 323leaf node 335least access privilege 181left child 335left justification 239left justified 70left justify 67left justifying strings in a field 248left subtree 335left-shift operator (<<) 270legacy code 176length modifier 240library function 4

LIFO (last-in, first-out) 94, 323<limits.h> header file 98, 273__LINE__, predefined symbolic constant

349#line preprocessor directive 348linear data structure 314linear data structures 335linear run time 379linear search 149, 150link (pointer in a self-referential structure)

313link phase 5linkage 107linkage of an identifier 108linked list 168, 259, 312, 314linker 7, 22, 357linker error 357linking 7links 314Linux 5, 6, 7, 16

shell prompt 8Linux operating system 17, 17list debugger command 439literal 21, 27literal characters 239live-code approach 2ll or LL for a long long int 359-lm command line option for using the

math library 67load phase 5loader 7loading 7local variable 86, 108, 135locale 98<locale.h> 98Locals window 430Locals window (Visual Studio debugger)

431log function 86log10 function 86log2n comparisons 340logic error 61, 80, 128, 268, 437logical AND operator (&&) 77, 272logical negation (NOT) operator (!) 77,

78logical OR operator (||) 77logical page 250long 73long double 93long int 93long long int 93loop 61loop continuation condition 58, 61, 62,

63, 73looping 61lowercase letter 97lvalue ("left value") 80, 124

MMac OS X 16, 18machine dependent 270machine independent 2machine language 7machine language code 7Macintosh 18macro 98, 343, 344

complex 404defined in 353

Page 24: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

454 Index

macro (cont.)definition 344expansion 345identifier 344with arguments 344

main 21make 358makefile 358malloc function 313, 362margin indicator bar 428mask 272, 272math library functions 98<math.h> header file 66, 86, 98maximum 90m-by-n array 155mean 144median 144member 260member name (bit field) 279members 260memchr function 232, 234memcmp function 232, 234memcpy function 232, 232memmove function 233memory 7memory access violation 177memory addresses 168memory allocation 98memory functions of the string handling

library 231, 232memory utilization 279memset function 232, 235menu-driven system 202merge sort algorithm 387, 388, 392merge two arrays 387message 21Microsoft Visual Studio 6, 396MinGW (Minimalist GNU for Win-

dows) 396mixed-type expressions 92mixing declarations and executable code

397mode 144module 84Mozilla Foundation 17multidimensional array 155, 156, 157multiple selection statement 39, 71multiple-source-file programs 108, 109multiple source files 356, 357multiple-subscripted array 155multiple-word variable name 25multiplication 27, 28multiplicative operators 48Multipurpose sorting program using

function pointers 199

Nn factorial (n!) 113n! 113name 59, 124name of a control variable 59name of an array 123natural logarithm 86negative value 376negative binary numbers 368nested if...else statement 42, 43nested parentheses 28, 30nesting 49

newline (\n) 22, 40, 134, 206, 208, 209,256

NeXTSTEP operating system 18nodes 313, 314non-constant pointer to constant data

177, 178, 179non-constant pointer to non-constant da-

ta 177nonfatal error 91NULL 169, 190, 194, 288, 313, 320null character ('\0') 133, 134, 178, 194,

207NULL pointer 362null-terminated string 194Number Systems Appendix 368numeric codes 225

OO(1) 379O(n log n) time 392O(n) time 379O(n2) time 380, 383, 387object 5object code 7object-oriented programming (OOP) 18,

87, 5object program 22Objective-C 18Objective-C programming language 5octal (base-8) number system 369octal number 209, 215, 239off-by-one error 61offset 190, 300one’s complement 276one’s complement notation 376ones position 369open a file 288open file table 286Open Handset Alliance 18open source 17, 18operand 27operating system 2, 16, 18operator precedence 34operator precedence chart 365Operator sizeof when applied to an ar-

ray name returns the number of bytesin the array 185

operators 51order 38order of evaluation of operands 118order of operands of operators 119OS X 18outer block 110out-of-bounds array elements 165oval symbol 39overflow 360

Ppackets in a computer network 329padding 280page layout software 206parameter 87parameter list 89parameter of a function 88parameter passing 176parameter types 184parent node 335

parentheses () 28, 34pass-by-reference 138, 139, 168, 172,

174, 176, 180, 182pass-by-value 172, 174, 176, 180passing an array 139passing an array element 139Passing arrays and individual array ele-

ments to functions 140percent sign (%) 27performance 4performance requirements 109PHP 5pipe symbol (|) 352piping 352pointer 168, 170, 172pointer arithmetic 188, 191pointer arrow (->) operator 262pointer comparisons 190pointer expression 190pointer notation 174, 190, 193pointer parameter 173pointer subscripting 191pointer to a function 199pointer to pointer (double indirection)

320pointer to the structure 262pointer to void (void *) 190, 313pointer variable 181, 182pointer/offset notation 190pointer/subscript notation 191poll 129polynomial 30, 31pop 323pop off a stack 94portability 4Portability Tips overview xviiiportable 4portable code 4portable programs 2position number 123positional notation 369positional value 369, 370positional values in the decimal number

system 370postdecrement 52postfix increment and decrement opera-

tors 52postincrement 52, 54postorder 336postOrder traversal 339, 340pow (power) function 30, 66, 67, 86power 86#pragma 347#pragma processor directive 347precedence 28, 124, 170precedence of arithmetic operators 29, 34precision 48, 67, 239, 239, 241predecrement operator 52predefined symbolic constants 348predicate function 320prefix increment and decrement operators

52preincrement operator 52preincrementing 53preincrementing vs. postincrementing 53preorder 336preOrder traversal 339preprocess phase 5preprocessor 7, 97

Page 25: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

Index 455

preprocessor directive 7, 343, 346principle of least privilege 109, 142, 176,

180, 184, 185print characters 210print debugger command 440printf 239printf 287printf function 21Printing a string one character at a time

using a non-constant pointer to con-stant data 178

printing character 212Printing positive and negative numbers

with and without the + flag 248probability 99Processing a queue 329program execution stack 94Program to simulate the game of craps

104programmer-defined function 84Programmer-defined maximum function

90prompt 25pseudo-random numbers 102push 323, 327push onto a stack 94putchar 217, 287puts 219puts function 35

Qquadratic run time 380queue 168, 259, 312, 329, 329Quick Info box 429quit debugger command 441

Rr file open mode 291r+ file open mode 291, 292radians 86raise 360rand 99RAND_MAX 99, 103random number 98random number generation 195random-access file 296, 299randomizing 102range checking 82rb file open mode 291rb+ file open mode 291readability 34, 60record 180, 287rectangle symbol 39recursion 112, 119

recursion step 113recursive call 113, 114recursive calls to method fibonacci

118recursive definition 113recursive evaluation 114recursive function 112vs. iteration 119

red breakpoint circle, solid 428redirect input from a file 352redirect input or output 239redirect input symbol < 352redirect output symbol > 353

redundant parentheses 30register 108reinventing the wheel 4, 84relational operators 31reliable integer division 409remainder 86remainder operator (%) 27, 99repetition statement 38, 43replacement text 128, 344requirements 109reserved word 34restrict 409restricted pointer 409return 172return from a function 85return key 7return statement 88, 90return type 184return value type 88return without expression 411reusable software 5Richards, Martin 2right brace (}) 21, 22right child 335right justification 239right justified 67, 245right subtree 335right-justifying integers 245Right-justifying integers in a field 245right-shift (>>) operator 271Ritchie, D. 2Rolling a six-sided die 6000 times 100root node of a binary tree 335rounded 49rounding 113, 239rounding toward negative infinity 409rounding toward zero 409rows 155rules of operator 28run debugger command 438rvalue (“right value”) 80

Ssavings account example 65scalable 128scalar 139scalars 182scaling 99scaling factor 99, 104scan characters 252scan set 254scanf 239scanf function 26scanf_s function 165scientific notation 241scope 346scope of an identifier 107, 108, 108, 109Scoping example 110screen 8search functions of the string handling li-

brary 225search key 150searching 149, 151searching a binary tree 340searching strings 221second-degree polynomial 31secondary storage device 7seed 102

seed the rand function 102SEEK_CUR 302SEEK_END 302SEEK_SET 300, 302segmentation fault 27, 177segmentation violations 360selection sort algorithm 380, 381, 383selection statement 40selection structure 38self-referential structure 260semicolon (;) 21, 34sentinel-controlled repetition 58sentinel value 46, 48sequence structure 38, 39sequential access file 287sequential execution 38sequential file 287set debugger command 442<setjmp.h> 98shell prompt on Linux 8shift 99Shifted, scaled integers produced by 1 +rand() % 6 99

shifting value 104short 73, 92short-circuit evaluation 78sibling 335side effect 98, 109, 119SIGABRT 360SIGFPE 360SIGILL 360SIGINT 360signal 360Signal handling 361signal handling library 360signal value 46<signal.h> 98, 360signed decimal integer 240SIGSEGV 360SIGTERM 360simple condition 77simulation 99, 99, 195sin function 86sine 86single quote (') character 244single-selection statement 39single-entry/single-exit control statements

40single-subscripted array 177, 184sinking sort 142size_t 126, 222, 225sizeof operator 185, 261, 313, 346small circle symbol 39smartphone 18software engineering 76, 109, 184Software Engineering Observations over-

view xviiisoftware reusability 4, 87, 184, 357Solution Configurations combobox 427sort algorithms

insertion sort 384merge sort 387selection sort 380

sort key 379sorting 142sorting data 379SourceForge 17space 256space flag 249

Page 26: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

456 Index

special characters 207split the array in merge sort 387sprintf 217, 220sqrt function 85square brackets ([]) 123square root 86srand 102sscanf 217, 220stack 94, 168, 259, 312, 323stack frame 94stack overflow 95Stack program 323Standard C 3standard data types 186standard error (stderr) 239standard error stream 286standard error stream (stderr) 8standard input 26, 217, 352standard input stream 286standard input stream (stdin) 8, 239standard input/output header (stdio.h)

21standard input/output library (stdio)

217standard libraries 7standard library

header 97, 97, 343Standard Library documentation 4standard output 352standard output stream 286standard output stream (stdout) 8, 239standard version of C 3statement 21, 38statement terminator (;) 21statements

return 88static 108static 108, 110, 136static array 127Static arrays are automatically initialized

to zero if not explicitly initialized bythe programmer 136

_Static_assert 349static data structures 362static storage duration 108<stdarg.h> 98, 353stdbool.h 79, 401<stddef.h> 98<stddef.h> header 169stderr (the standard error device) 8, 286stdin (standard input stream) 8, 217,

286stdint.h 396<stdio.h> header file 21, 70, 98, 109,

217, 239, 286, 346<stdlib.h> header file 98, 99, 213,

343, 358, 362stdout (standard output stream) 8, 286,

287, 289step debugger command 444Step Into command (debugger) 432Step Out command (debugger) 434Step Over command (debugger) 433StepStone 18stepwise refinement 195storage class 107storage class of an identifier 108storage class specifiers 108

auto 108

storage duration 107, 108, 136storage duration of an identifier 108storage unit boundary 282stored array 314straight-line form 28strcat function 223strchr function 226strcmp function 224, 225strcpy function 222strcspn function 225, 227stream 239, 286strerror 236string 21, 207string array 194string comparison functions 224string constant 207string conversion functions 213string is a pointer 207string literal 134, 207string literals separated only by whitespace

134string manipulation functions of the

string handling library 221, 225string processing 133string processing function 98<string.h> header 222<string.h> header file 98strlen function 236strncat function 222, 223strncmp function 224, 225strncpy function 222Stroustrup, Bjarne 4strpbrk 228strpbrk function 226, 228strrchr function 226, 228strspn function 225, 229strstr function 226, 229strtod function 214strtok function 226, 230strtol function 214, 215strtoul function 214, 216struct 123, 259structure 180, 259structure definition 260structure member (.) operator 262, 263,

268Structure member operator and structure

pointer operator 263structure pointer (->) operator 262, 263,

268structure tag name 259, 261structure type 259structure variable 261structured programming 2, 20, 38, 363Structures 259Student poll analysis program 130student poll program 130subscript 124, 131subscript notation 180subtract an integer from a pointer 188subtracting one pointer from another 188subtracting two pointers 189suffix

floating point 360integer 359

sum of the elements of an array 129survey data analysis 144, 148Survey data analysis program 145swapping values 380, 384

switch multiple-selection statement 39,68, 71with break 72

symbol 39symbol value 369symbolic constant 70, 128, 343, 344, 348syntax error 7, 54, 81

Ttab 22, 23, 40, 250, 256table 155tablet computer 18tabular format 125tail of a queue 312, 329tan 86tangent 86temporary <double> representation 66temporary copy 48terminating null character 133, 134, 207,

208, 218, 243termination request 360ternary operator 41, 119text processing 206tgmath.h 396Thompson, Ken 2_Thread_local storage class specifier

108time 98__STDC__, predefined symbolic constant

349__TIME__, predefined symbolic constant

349<time.h> 98token 226, 348tokenizing strings 221tokens 230tolower function 211top of a stack 312top-down stepwise refinement 195toupper function 177, 211trailing zeros 242transaction-processing program 303transaction-processing systems 297transfer of control 38trap 360trap a SIGINT 360traversing a binary tree 336Treating character arrays as strings 135tree 30, 168, 259, 335trigonometric cosine 86trigonometric sine 86trigonometric tangent 86true 31truth 77truth table 77Turing Machine 38two’s complement 376two’s complement notation 376two-dimensional array 194twos position 371type checking 91type mismatch 177typedef 264type-generic macro 410typesetting systems 206

Page 27: Introduction to C Programming - Managementboek.nl€¦ · Introduction to C Programming Objectives In this chapter you’ll: Write simple C programs. Use simple input and output statements

Index 457

Uu or U for an unsigned int 359unary operator 48, 54, 169unary operator sizeof 185unconditional branch 363#undef 348#undef preprocessor directive 346underscore (_) 25union 268, 269UNIX 2, 70unnamed bit field 280unnamed bit field with a zero width 282unresolved references 357unsafe macro 350unsigned 102unsigned decimal integer 240unsigned hexadecimal integer 240unsigned int 93unsigned integer 270unsigned long int 216unsigned long long int 114, 115, 116unsigned octal integer 240unsigned short 93uppercase letter 97usual arithmetic conversion rules 92utility function 98

Vva_arg 354

va_copy macro 411va_end 355va_list 354va_start 354validate data 82value 124variable 24variable arguments header stdarg.h 353variable initialization 194variable-length argument list 353, 354variable-length array (VLA) 162, 405vertical spacing 60vertical tab ('\v') 209vi 6Visual C# programming language 5, 5Visual Studio 396Visual C++ programming language 5Visual Studio 6

Quick Info box 429void * (pointer to void) 190, 232, 313

Ww file open mode 291w+ file open mode 291w+ file update mode 291watch debugger command 446Watch window (Visual Studio debugger)

430, 431wb file open mode 291wb+ file open mode 291

wchar.h 396wctype.h 396while repetition statement 43white-space character 21, 40, 256whitespace

string literals separated 134width of a bit field 279, 282Wikipedia 5Windows 16, 360Windows operating system 17Windows Phone 7 16worst-case runtime for an algorithm 379Wozniak, Steve 17writing to a file 289

Xx 244Xerox PARC (Palo Alto Research Center)

17

Yyellow arrow in break mode 429

Z0 (zero) flag 250zeroth element 123