Lecture Notes c++ Programming

lecture notes on object oriented programming using c++ and bject oriented programming c++ lecture notes pdf free download
HowdyNicolson Profile Pic
Published Date:09-07-2017
Your Website URL(Optional)
Fundamentals of ++ C Programming Richard L. Halterman School of Computing Southern Adventist University June 2, 2017 DRAFT1 Chapter 1 The Context of Software Development A computer program, from one perspective, is a sequence of instructions that dictate the flow of electri- cal impulses within a computer system. These impulses affect the computer’s memory and interact with the display screen, keyboard, mouse, and perhaps even other computers across a network in such a way as to produce the “magic” that permits humans to perform useful tasks, solve high-level problems, and play games. One program allows a computer to assume the role of a financial calculator, while another transforms the machine into a worthy chess opponent. Note the two extremes here: • at the lower, more concrete level electrical impulses alter the internal state of the computer, while • at the higher, more abstract level computer users accomplish real-world work or derive actual plea- sure. So well is the higher-level illusion achieved that most computer users are oblivious to the lower-level activity (the machinery under the hood, so to speak). Surprisingly, perhaps, most programmers today write software at this higher, more abstract level also. An accomplished computer programmer can develop sophisticated software with little or no interest or knowledge of the actual computer system upon which it runs. Powerful software construction tools hide the lower-level details from programmers, allowing them to solve problems in higher-level terms. The concepts of computer programming are logical and mathematical in nature. In theory, computer programs can be developed without the use of a computer. Programmers can discuss the viability of a program and reason about its correctness and efficiency by examining abstract symbols that correspond to the features of real-world programming languages but appear in no real-world programming language. While such exercises can be very valuable, in practice computer programmers are not isolated from their machines. Software is written to be used on real computer systems. Computing professionals known as software engineers develop software to drive particular systems. These systems are defined by their underlying hardware and operating system. Developers use concrete tools like compilers, debuggers, and profilers. This chapter examines the context of software development, including computer systems and tools. ©2017 Richard L. Halterman Draft date: June 2, 20171.1. SOFTWARE 2 1.1 Software A computer program is an example of computer software. Software makes a computer a truly universal machine transforming it into the proper tool for the task at hand. One can refer to a program as a piece of software as if it were a tangible object, but software is actually quite intangible. It is stored on a medium. A hard drive, a CD, a DVD, and a USB pen drive are all examples of media upon which software can reside. The CD is not the software; the software is a pattern on the CD. In order to be used, software must be stored in the computer’s memory. Typically computer programs are loaded into memory from a medium like the computer’s hard disk. An electromagnetic pattern representing the program is stored on the computer’s hard drive. This pattern of electronic symbols must be transferred to the computer’s memory before the program can be executed. The program may have been installed on the hard disk from a CD or from the Internet. In any case, the essence that was transferred from medium to medium was a pattern of electronic symbols that direct the work of the computer system. These patterns of electronic symbols are best represented as a sequence of zeroes and ones, digits from the binary (base 2) number system. An example of a binary program sequence is 10001011011000010001000001001110 To the underlying computer hardware, specifically the processor, a zero here and three ones there might mean that certain electrical signals should be sent to the graphics device so that it makes a certain part of the display screen red. Unfortunately, only a minuscule number of people in the world would be able to produce, by hand, the complete sequence of zeroes and ones that represent the program Microsoft Word for an Intel-based computer running the Windows 8 operating system. Further, almost none of those who could produce the binary sequence would claim to enjoy the task. The Word program for older Mac OS X computers using a PowerPC processor works similarly to the Windows version and indeed is produced by the same company, but the program is expressed in a com- pletely different sequence of zeroes and ones The Intel Core i7 processor in the Windows machine accepts a completely different binary language than the PowerPC processor in the Mac. We say the processors have their own machine language. 1.2 Development Tools If very few humans can (or want) to speak the machine language of the computers’ processors and software is expressed in this language, how has so much software been developed over the years? Software can be represented by printed words and symbols that are easier for humans to manage than binary sequences. Tools exist that automatically convert a higher-level description of what is to be done ++ into the required lower-level code. Higher-level programming languages like C allow programmers to express solutions to programming problems in terms that are much closer to a natural language like English. Some examples of the more popular of the hundreds of higher-level programming languages that have been devised over the past 60 years include FORTRAN, COBOL, Lisp, Haskell, C, Perl, Python, Java, and C. Most programmers today, especially those concerned with high-level applications, usually do not worry about the details of underlying hardware platform and its machine language. One might think that ideally such a conversion tool would accept a description in a natural language, such as English, and produce the desired executable code. This is not possible today because natural languages are quite complex compared to computer programming languages. Programs called compilers that translate one computer language into another have been around for over 60 years, but natural language ©2017 Richard L. Halterman Draft date: June 2, 20171.2. DEVELOPMENT TOOLS 3 processing is still an active area of artificial intelligence research. Natural languages, as they are used by most humans, are inherently ambiguous. To understand properly all but a very limited subset of a natural language, a human (or artificially intelligent computer system) requires a vast amount of background knowledge that is beyond the capabilities of today’s software. Fortunately, programming languages provide a relatively simple structure with very strict rules for forming statements that can express a solution to any problem that can be solved by a computer. ++ Consider the following program fragment written in the C programming language: subtotal = 25; tax = 3; total = subtotal + tax; ++ These three lines do not make up a complete C program; they are merely a piece of a program. The statements in this program fragment look similar to expressions in algebra. We see no sequence of bi- nary digits. Three words, subtotal, tax, and total, called variables, are used to hold information. Mathematicians have used variables for hundreds of years before the first digital computer was built. In programming, a variable represents a value stored in the computer’s memory. Familiar operators (= and +) are used instead of some cryptic binary digit sequence that instructs the processor to perform the operation. ++ Since this program is expressed in the C language, not machine language, it cannot be executed directly ++ ++ on any processor. A C compiler is used to translate the C code into machine code. The higher-level language code is called source code. The compiled machine language code is called the target code. The compiler translates the source code into the target machine language. ++ The beauty of higher-level languages is this: the same C source code can be compiled to different ++ target platforms. The target platform must have a C compiler available. Minor changes in the source code may be required because of architectural differences in the platforms, but the work to move the program from one platform to another is far less than would be necessary if the program for the new platform had to be rewritten by hand in the new machine language. Just as importantly, when writing the program the ++ human programmer is free to think about writing the solution to the problem in C , not in a specific machine language. Programmers have a variety of tools available to enhance the software development process. Some common tools include: • Editors. An editor allows the user to enter the program source code and save it to files. Most pro- gramming editors increase programmer productivity by using colors to highlight language features. The syntax of a language refers to the way pieces of the language are arranged to make well-formed sentences. To illustrate, the sentence The tall boy runs quickly to the door. uses proper English syntax. By comparison, the sentence Boy the tall runs door to quickly the. is not correct syntactically. It uses the same words as the original sentence, but their arrangement does not follow the rules of English. Similarly, programmers must follow strict syntax rules to create well-formed computer programs. Only well-formed programs are acceptable and can be compiled and executed. Some syntax-aware editors can use colors or other special annotations to alert programmers of syntax errors before the program is compiled. ©2017 Richard L. Halterman Draft date: June 2, 20171.2. DEVELOPMENT TOOLS 4 Figure 1.1 Source code to target code sequence Concept of (Design problem program logic) solution Programmer’s Editor (Edit) responsibility include io using namespace std; Source code int main() srand(23); int n; n = rand(); proc(n); Library declarations (source code) istream cin; ostream cout; int rand(); Preprocessor (Preprocess) void sand(); typedef unsigned U define NULL (0) include io using namespace std; Enhanced int main() srand(23); int n; source code n = rand(); proc(n); Automated Compiler (Compile) by tools 101100010101 Object code 000010001100 1100001111010100 0011101101110011 1000000010000110 0111000000111111 1100111011001001 0000100001111000 0001110111101101 Pre-compiled 1101111011111010 libraries (object code) 11000011110 00111011011 1000000010000110 Linker 0111000000111111 (Link) 1100111011001001 0000100001111000 0001110111101101 1101111011111010 101100010101 000010001100 1100001111010100 0011101101110011 Executable 1000000010000110 0111000000111111 1100111011001001 program 0000100001111000 0001110111101101 1101111011111010 ©2017 Richard L. Halterman Draft date: June 2, 20171.2. DEVELOPMENT TOOLS 5 • Compilers. A compiler translates the source code to target code. The target code may be the machine language for a particular platform or embedded device. The target code could be another source ++ ++ language; for example, the earliest C compiler translated C into C, another higher-level language. ++ The resulting C code was then processed by a C compiler to produce an executable program. C ++ compilers today translate C directly into machine language. ++ The complete set of build tools for C includes a preprocessor, compiler, and linker: – Preprocessor—adds to or modifies the contents of the source file before the compiler begins processing the code. We use the services of the preprocessor mainly toinclude information about library routines our programs use. ++ – Compiler—translates C source code to machine code. – Linker—combines the compiler-generated machine code with precompiled library code or compiled code from other sources to make a complete executable program. Most compiled ++ C code is incapable of running by itself and needs some additional machine code to make a complete executable program. The missing machine code has been precompiled and stored in a repository of code called a library. A program called a linker combines the programmer’s compiled code and the library code to make a complete program. We generally do not think about the preprocessor, compiler, and linker working as three separate programs (although they do); the tools we use make it appear as only one process is taking place: translating our source code to an executable program. • Debuggers. A debugger allows a programmer to more easily trace a program’s execution in order to locate and correct errors in the program’s implementation. With a debugger, a developer can simultaneously run a program and see which line in the source code is responsible for the program’s current actions. The programmer can watch the values of variables and other program elements to see if their values change as expected. Debuggers are valuable for locating errors (also called bugs) and repairing programs that contain errors. (See Section 4.6 for more information about programming errors.) • Profilers. A profiler collects statistics about a program’s execution allowing developers to tune ap- propriate parts of the program to improve its overall performance. A profiler indicates how many times a portion of a program is executed during a particular run, and how long that portion takes to execute. Profilers also can be used for testing purposes to ensure all the code in a program is actually being used somewhere during testing. This is known as coverage. It is common for software to fail after its release because users exercise some part of the program that was not executed anytime during testing. The main purpose of profiling is to find the parts of a program that can be improved to make the program run faster. The programming components of the development process are illustrated in Figure 1.1. Many developers use integrated development environments (IDEs). An IDE includes editors, debug- ++ gers, and other programming aids in one comprehensive program. Examples of IDEs for C include Microsoft’s Visual Studio 2015, the Eclipse Foundation’s Eclipse CDT, and Apple’s XCode. Despite the plethora of tools (and tool vendors’ claims), the programming process for all but trivial programs is not automatic. Good tools are valuable and certainly increase the productivity of developers, but they cannot write software. There are no substitutes for sound logical thinking, creativity, common sense, and, of course, programming experience. ©2017 Richard L. Halterman Draft date: June 2, 20171.3. LEARNING PROGRAMMING WITH C++ 6 1.3 Learning Programming with C++ ++ ++ Bjarne Stroustrup of AT&T Bell Labs created C in the mid 1980s. C is an extension of the programming language C, a product of AT&T Bell Labs from the early 1970s. C was developed to write the Unix operating system, and C is widely used for systems-level software and embedded systems development. ++ C initially provided object-oriented programming features (see Chapter 13 and Chapter 14) and later ++ ++ added generic programming capabilities. C ’s close relationship to C allows C programs to utilize a large collection of code developed in C. ++ C is widely used in industry for commercial software development. It is an industrial strength pro- gramming language used for developing complex systems in business, science, and engineering. Examples ++ of software written in C include Microsoft Windows 8, Microsoft Office, macOS, and Adobe Creative Suite. ++ In order to meet the needs of commercial software development and accomplish all that it does, C ++ itself is complex. While experienced programmers can accomplish great things with C , beginners some- times have a difficult time with it. Professional software developers enjoy the flexible design options that ++ C permits, but beginners need more structure and fewer options so they can master simpler concepts before moving on to more complex ones. ++ This book does not attempt to cover all the facets of the C programming language. Experienced ++ programmers should look elsewhere for books that cover C in much more detail. The focus here is on introducing programming techniques and developing good habits. To that end, our approach avoids some of ++ the more esoteric features of C and concentrates on the programming basics that transfer directly to other imperative programming languages such as Java, C, and Python. We stick with the basics and explore ++ more advanced features of C only when necessary to handle the problem at hand. 1.4 Exercises 1. What is a compiler? 2. How is compiled code different from source code? ++ 3. What tool does a programmer use to produce C source code? ++ 4. What tool(s) does a programmer use to convert C source code into executable machine code? 5. What does the linker do? 6. Does the linker deal with files containing source code or or machine language code? 7. What does the preprocessor do to source code? 8. List several advantages developing software in a higher-level language has over developing software in machine language. 9. How can an IDE improve a programmer’s productivity? ++ 10. Name a popular C IDE is used by programmers developing for Microsoft Windows. ++ 11. Name a popular C IDE is used by programmers developing for Apple macOS. ©2017 Richard L. Halterman Draft date: June 2, 20177 Chapter 2 Writing a C++ Program ++ Properly written C programs have a particular structure. The syntax must be correct, or the compiler ++ will generate error messages and not produce executable machine language. This chapter introduces C by providing some simple example programs and associated fundamental concepts. Most of the concepts presented in this chapter are valid in many other programming languages as well. While other languages may implement the concepts using slightly different syntax, the ideas are directly transferable to other languages like C, Java, C, and Ada. 2.1 General Structure of a Simple C++ Program ++ Listing 2.1 (simple.cpp) is one of the simplest C programs that does something: Listing 2.1: simple.cpp include iostream int main() std::cout "This is a simple C++ program\n"; You can type the text as shown in Listing 2.1 (simple.cpp) into an editor and save it to a file named simple.cpp. The actual name of the file is irrelevant, but the name “simple” accurately describes the nature ++ of this program. The extension .cpp is a common extension used for C source code. After creating this file with a text editor and compiling it, you can run the program. The program prints the message This is a simple C++ program Listing 2.1 (simple.cpp) contains four non-blank lines of code: • include iostream ++ This line is a preprocessing directive. All preprocessing directives within C source code begin with a symbol. This one directs the preprocessor to add some predefined source code to our existing ©2017 Richard L. Halterman Draft date: June 2, 20172.2. EDITING, COMPILING, AND RUNNING THE PROGRAM 8 source code before the compiler begins to process it. This process is done automatically and is invisible to us. ++ Here we want to use an object from theiostream library, a collection precompiled C code that ++ C programs (like ours) can use. The iostream library contains elements that handle input and output (I/O)—printing to the display, getting user input from the keyboard, and dealing with files. ++ One of the items used in Listing 2.1 (simple.cpp),std::cout, is not part of the C language itself. ++ This item, along with other things related to input and output, were developed in C , compiled, and stored in the iostream library. The compiler needs to be aware of these iostream items so it can compile our program. The include directive specifies a file, called a header, that contains the specifications for the library code. The compiler checks how we use std::cout within our code against its specification in theiostream header to ensure that we are using the library code correctly. Most of the programs we write use this include iostream directive, and some programs we will write in the future willinclude other headers as well. • int main() This specifies the real beginning of our program. Here we are declaring a function namedmain. All ++ C programs must contain this function to be executable. Details about the meaning of int and the parentheses will appear in later chapters. More general information about functions appear in Chapter 8 and Chapter 9. The opening curly brace at the end of the line marks the beginning of the body of a function. The body of a function contains the statements the function is to execute. • std::cout "This is a simple C++ program\n"; The body of our main function contains only one statement. This statement directs the executing program to print the message This is a simple C++ program on the screen. A statement is the ++ fundamental unit of execution in a C program. Functions contain statements that the compiler ++ translates into executable machine language instructions. C has a variety of different kinds of statements, and the chapters that follow explore these various kinds of statements. All statements in ++ C end with a semicolon (;). A more detailed explanation of this statement appears below. • The closing curly brace marks the end of the body of a function. Both the open curly brace and close curly brace are required for every function definition. Note which lines in the program end with a semicolon (;) and which do not. Do not put a semicolon after the include preprocessor directive. Do not put a semicolon on the line containingmain, and do not put semicolons after the curly braces. 2.2 Editing, Compiling, and Running the Program ++ ++ C programmers have two options for C development environments. One option involves a command- line environment with a collection of independent tools. The other option is to use an IDE (see Section 1.2) which combines all the tools into a convenient package. Visual Studio is the dominant IDE on the Microsoft ©2017 Richard L. Halterman Draft date: June 2, 20172.3. VARIATIONS OF OUR SIMPLE PROGRAM 9 Windows platform, and Apple Mac developers often use the XCode IDE. Appendix A provides an overview ++ of how to use the Visual Studio 2015 IDE to develop a simple C program. The myriad of features and configuration options in these powerful IDEs can be bewildering to those learning how to program. In a command-line environment the programmer needs only type a few simple commands into a console window to edit, compile, and execute programs. Some developers prefer the simplicity and flexibility of command-line build environments, especially for less complex projects. One prominent command-line build system is the GNU Compiler Collection (http://gcc.gnu. ++ org), or GCC for short. The GCC C++ compiler, called g++, is one of most C standards conforming ++ compilers available. The GCC C compiler toolset is available for the Microsoft Windows, Apple Mac, and Linux platforms, and it is a free, open-source software project with a world-wide development team. ++ Appendix B provides an overview of how to use the GCC C compiler. Visual Studio and XCode offer command line development options as well. Appendix B provides an overview of the Visual Studio command line development process. 2.3 Variations of our simple program Listing 2.2 (simple2.cpp) shows an alternative way of writing Listing 2.1 (simple.cpp). Listing 2.2: simple2.cpp include iostream using std::cout; int main() cout "This is a simple C++ program\n"; The using directive in Listing 2.2 (simple2.cpp) allows us to use a shorter name for the std::cout printing object. We can omit thestd:: prefix and use the shorter name,cout. This directive is optional, but if we omit it, we must use the longer name. The namestd stands for “standard,” and thestd prefix indicates thatcout is part of a collection of names called the standard namespace. Thestd namespace ++ holds names for all the standard C types and functions that must be available to all standards-conforming ++ C development environments. Components outside the standard library provided by third-party develop- ers reside in their own separately-named namespaces. These include open-source projects and commercial libraries. ++ Listing 2.3 (simple3.cpp) shows another way to use the shorter name forcout within a C program. Listing 2.3: simple3.cpp include iostream using namespace std; int main() cout "This is a simple C++ program\n"; While Listing 2.2 (simple2.cpp) made the name cout known to the compiler via its focused using di- rective, Listing 2.3 (simple3.cpp) provides a blanket using directive that makes all names in the std ©2017 Richard L. Halterman Draft date: June 2, 20172.3. VARIATIONS OF OUR SIMPLE PROGRAM 10 namespace available to the compiler. This approach offers some advantages for smaller programs, such as examples in books and online tutorials. This blanketusing directive allows programmers to use shorter names as in the more more focusedusing directives, and it also can use fewer lines of code than the more focusedusing directives, especially when the program uses multiple elements from thestd namespace. Our choice ofusing directives (or not) makes no difference in our final product, the executable pro- gram. The compiler generates the same machine language code for all three versions—nousing, focused using, and blanketusing. We thus must select an approach that enhances our ability to write and manage our software projects. It is important to note that while this blanket using approach has its place, its use generally is dis- couraged for more complex software projects. At this point we cannot fully appreciate the rationale for avoiding theusing namespace std directive, but later, in Section 20.6, we will have enough experi- ence to understand the disadvantages of the blanketusing namespace std directive. We will strive for best practices from the start and avoid the blanket using statement. We generally will use the full names of the elements in thestd namespace and use the more focusedusing directives in our code when it makes sense to do so. The statement in themain function in any of the three versions of our program uses the services of an object calledstd::cout. Thestd::cout object prints text on the computer’s screen. The text of the ++ message as it appears in the C source code is called a string, for string of characters. Strings are enclosed within quotation marks ("). The symbols make up the insertion operator. You can think of the message to be printed as being “inserted” into the cout object. The cout object represents the output stream; that is, text that the program prints to the console window. The end of the message contains the symbol sequence\n. This known as a character escape sequence, and this combination of backslash and the letter n represents the newline character. It indicates that the printing on that line is complete, and any subsequent printing should occur on the next line. This newline character effectively causes the cursor to move down to the next line. If you read the statement from left to right, the cout object, which is responsible for displaying text on the screen, receives the text to print terminated with the newline character to move to the next line. For simplicity, we’ll refer to this type of statement as a print statement, even though the word print does not appear anywhere in the statement. ++ With minor exceptions, any statement in C must appear within a function definition. Our single print statement appears within the function namedmain. Any function, including main, may contain multiple statements. In Listing 2.4 (arrow.cpp), six print statements draw an arrow on the screen: Listing 2.4: arrow.cpp include iostream int main() std::cout " \n"; std::cout " \n"; std::cout " \n"; std::cout " \n"; std::cout " \n"; std::cout " \n"; The output of Listing 2.4 (arrow.cpp) is ©2017 Richard L. Halterman Draft date: June 2, 20172.3. VARIATIONS OF OUR SIMPLE PROGRAM 11 Each print statement “draws” a horizontal slice of the arrow. The six statements std::cout " \n"; std::cout " \n"; std::cout " \n"; std::cout " \n"; std::cout " \n"; std::cout " \n"; constitute the body of themain function. The body consists of all the statements between the open curly brace () and close curly brace (). We say that the curly braces delimit the body of the function. The word delimit means to determine the boundaries or limits of something. The symbol determines the beginning of the function’s body, and the symbol specifies the end of the function’s body. We can rewrite Listing 2.4 (arrow.cpp) to achieve the same effect with only one long print statement as Listing 2.5 (arrow2.cpp) shows. Listing 2.5: arrow2.cpp include iostream int main() std::cout " \n" " \n" " \n" " \n" " \n" " \n"; At first, Listing 2.4 (arrow.cpp) and Listing 2.5 (arrow2.cpp) may appear to be identical, but upon closer inspection of this new program we see that std::cout appears only once within main, and only one ++ semicolon (;) appears withinmain. Since semicolons in C terminate statements, there really is only one statement. Notice that a single statement can be spread out over several lines. The statement withinmain appearing as std::cout " \n" " \n" " \n" " \n" " \n" " \n"; could have just as easily been written as std::cout " \n" " \n" " \n" " \n" " \n" " \n"; ©2017 Richard L. Halterman Draft date: June 2, 20172.4. TEMPLATE FOR SIMPLE C++ PROGRAMS 12 but the first way of expressing it better portrays how the output will appear. Read this second version carefully to convince yourself that the printed pieces will indeed flow to thestd::cout printing object in the proper sequence to produce the same picture of the arrow. Consider the mistake of putting semicolons at the end of each of the lines in the “one statement” version: std::cout " \n"; " \n"; " \n"; " \n"; " \n"; " \n"; If we put this code fragment inmain, the program will not compile. The reason is simple—the semicolon at the end of the first line terminates the statement on that line. The compiler expects a new statement on the next line, but " \n"; ++ is not a complete legal C statement since the operator is missing the std::cout object. The string" \n" has nothing to “flow into.” Listing 2.6 (empty.cpp) is even simpler than Listing 2.1 (simple.cpp). Listing 2.6: empty.cpp int main() Since Listing 2.6 (empty.cpp) does not use thestd::cout object and so does not need theinclude ++ and using directives. While it is legal and sometimes even useful in C to write functions with empty bodies, such functions will do nothing when they execute. Listing 2.6 (empty.cpp) with its empty main ++ function is, therefore, truly the simplest executable C program we can write, but it does nothing when we runs it ++ In general, a C program may contain multiple functions, but we defer such generality until Chapter 9. For now, we will restrict our attention to programs with only amain function. 2.4 Template for simple C++ programs For our immediate purposes all the programs we write will have the form shown in Figure 2.1. Our programs generally will print something, so we need the include directive that brings the std::cout definition fromiostream into our program. Depending on what we need our program to do, we may need additional include directives. The main function definition is required for an executable program, and we will fill its body with statements that make our program do as we wish. Later, our programs will become more sophisticated, and we will need to augment this simple template. ©2017 Richard L. Halterman Draft date: June 2, 20172.5. EXERCISES 13 ++ Figure 2.1 The general structure of a very simple C program. include directives int main() program statements 2.5 Exercises 1. What preprocessor directive is necessary to use statements with the std::cout printing stream object? 2. What statement allows the short namecout to be used instead ofstd::cout? 3. What does the namestd stand for? ++ 4. All C programs must have a function named what? 5. The body ofmain is enclosed within what symbols? 6. What operator directs information to thestd::cout output stream? ++ 7. Write a C program that prints your name in the console window. ++ 8. Write a C program that prints your first and last name in the console window. Your first name should appear on one line, and your last name appear on the next line. 9. What other files must you distribute with your executable file so that your program will run on a Windows PC without Visual Studio installed? ++ 10. Can a single statement in C span multiple lines in the source code? ©2017 Richard L. Halterman Draft date: June 2, 20172.5. EXERCISES 14 ©2017 Richard L. Halterman Draft date: June 2, 201715 Chapter 3 Values and Variables ++ In this chapter we explore some building blocks that are used to develop C programs. We experiment with the following concepts: • numeric values • variables • declarations • assignment • identifiers • reserved words In the next chapter we will revisit some of these concepts in the context of other data types. 3.1 Integer Values The number four (4) is an example of a numeric value. In mathematics, 4 is an integer value. Integers are whole numbers, which means they have no fractional parts, and an integer can be positive, negative, or zero. Examples of integers include 4,19, 0, and1005. In contrast, 4.5 is not an integer, since it is not a whole number. ++ ++ C supports a number of numeric and non-numeric values. In particular, C programs can use integer ++ values. It is easy to write a C program that prints the number four, as Listing 3.1 (number4.cpp) shows. Listing 3.1: number4.cpp include iostream int main() std::cout 4 '\n'; ©2017 Richard L. Halterman Draft date: June 2, 20173.1. INTEGER VALUES 16 Notice that unlike the programs we saw earlier, Listing 3.1 (number4.cpp) does not use quotation marks ("). The number 4 appears unadorned with no quotes. The expression '\n' represents a single newline ++ character. Multiple characters comprising a string appear in double quotes ("), but, in C , a single character represents a distinct type of data and is enclosed within single quotes ('). (Section 3.8 provides more ++ information about C characters.) Compare Listing 3.1 (number4.cpp) to Listing 3.2 (number4-alt.cpp). Listing 3.2: number4-alt.cpp include iostream int main() std::cout "4\n"; Both programs behave identically, but Listing 3.1 (number4.cpp) prints the value of the number four, while Listing 3.2 (number4-alt.cpp) prints a message containing the digit four. The distinction here seems unim- portant, but we will see in Section 3.2 that the presence or absence of the quotes can make a big difference in the output. The statement std::cout "4\n"; sends one thing to the output stream, the string"4\n". The statement std::cout 4 '\n'; sends two things to the output stream, the integer value 4 and the newline character'\n'. ©2017 Richard L. Halterman Draft date: June 2, 20173.1. INTEGER VALUES 17 ++ In published C code you sometimes will see a statement such as the following: std::cout 4 std::endl; This statement on the surface behaves exactly like the following statement: std::cout 4 '\n'; but the two expressions std::endl and '\n' do not mean exactly the same thing. Thestd::endl expression does involve a newline character, but it also performs some additional work that normally is not necessary. Programs that do significant printing may execute faster if they terminate their output lines with'\n' instead ofstd::endl. The difference in speed is neg- ligible when printing to the console, but the different can be great when printing to files or other output streams. For most of the programs we consider, the differ- ence in program execution speed between the two is imperceptible; nonetheless, we will prefer'\n' for printing newlines because it is a good habit to form (and it requires five fewer keystrokes when editing code). The three major modern computing platforms are Microsoft Windows, Apple ma- cOS, and Linux. Windows handles newlines differently from macOS and Linux. Historically, the character '\n' represents a new line, usually known as a line feed or LF for short, and the character '\r' means carriage return, or CR for short. The terminology comes from old-fashioned typewriters which feed a piece of paper into a roller on a carriage that moves to the left as the user types (so the imprinted symbols form left to right). At the end of a line, the user must advance the roller so as to move the paper up by one line (LF) and move the carriage back all the way to its left (CR). Windows uses the character sequence CR LF for new- lines, while macOS and Linux use LF. This can be an issue when attempting to edit text files written with an editor on one platform with an editor on a different platform. ++ The good news is that the C standard guarantees that the std::cout output ++ stream translates the '\n' character as it appears in C source code into the correct character sequence for the target platform. This means you can print'\n' viastd::cout, and it will behave identically on all the major platforms. ++ In C source code, integers may not contain commas. This means we must write the number two ++ thousand, four hundred sixty-eight as 2468, not 2,468. Modern C does support single quotes (') as digit separators, as in2'468. Using digit separators can improve the human comprehension reading large ++ numbers in C source code. In mathematics, integers are unbounded; said another way, the set of mathematical integers is infinite. ++ In C the range of integers is limited because all computers have a finite amount of memory. The exact ++ ++ range of integers supported depends on the computer system and particular C compiler. C on most 32-bit computer systems can represent integers in the range2,147,483,648 to +2,147,483,647. ++ What happens if you exceed the range of C integers? Try Listing 3.3 (exceed.cpp) on your system. Listing 3.3: exceed.cpp include iostream int main() std::cout -3000000000 '\n'; ©2017 Richard L. Halterman Draft date: June 2, 20173.2. VARIABLES AND ASSIGNMENT 18 Negative three billion is too large for 32-bit integers, however, and the program’s output is obviously wrong: 1294967296 ++ The number printed was not even negative Most C compilers will issue a warning about this statement. Section 4.6 explores errors vs. warnings in more detail. If the compiler finds an error in the source, it will not generate the executable code. A warning indicates a potential problem and does not stop the compiler from producing an executable program. Here we see that the programmer should heed this warning because the program’s execution produces meaningless output. This limited range of values is common among programming languages since each number is stored in a fixed amount of memory. Larger numbers require more storage in memory. In order to model the infinite ++ set of mathematical integers an infinite amount of memory would be needed As we will see later, C supports an integer type with a greater range. Section 4.8.1 provides some details about the implementation ++ of C integers. 3.2 Variables and Assignment ++ ++ In algebra, variables are used to represent numbers. The same is true in C , except C variables also can represent values other than numbers. Listing 3.4 (variable.cpp) uses a variable to store an integer value and then prints the value of the variable. Listing 3.4: variable.cpp include iostream int main() int x; x = 10; std::cout x '\n'; Themain function in Listing 3.4 (variable.cpp) contains three statements: • int x; ++ This is a declaration statement. All variables in a C program must be declared. A declaration specifies the type of a variable. The word int indicates that the variable is an integer. The name ++ of the integer variable is x. We say that variable x has type int. C supports types other than integers, and some types require more or less space in the computer’s memory. The compiler uses the declaration to reserve the proper amount of memory to store the variable’s value. The declaration enables the compiler to verify the programmer is using the variable properly within the program; for example, we will see that integers can be added together just like in mathematics. For some other data types, however, addition is not possible and so is not allowed. The compiler can ensure that a variable involved in an addition operation is compatible with addition. It can report an error if it is not. The compiler will issue an error if a programmer attempts to use an undeclared variable. The com- piler cannot deduce the storage requirements and cannot verify the variable’s proper usage if it not declared. Once declared, a particular variable cannot be redeclared in the same context. A variable may not change its type during its lifetime. ©2017 Richard L. Halterman Draft date: June 2, 20173.2. VARIABLES AND ASSIGNMENT 19 • x = 10; This is an assignment statement. An assignment statement associates a value with a variable. The key to an assignment statement is the symbol= which is known as the assignment operator. Here the value 10 is being assigned to the variablex. This means the value 10 will be stored in the memory location the compiler has reserved for the variable namedx. We need not be concerned about where the variable is stored in memory; the compiler takes care of that detail. After we declare a variable we may assign and reassign it as often as necessary. • std::cout x '\n'; This statement prints the variablex’s current value. Note that the lack of quotation marks here is very important. If x has the value 10, the statement std::cout x '\n'; prints10, the value of the variablex, but the statement std::cout "x" '\n'; printsx, the message containing the single letter x. The meaning of the assignment operator (=) is different from equality in mathematics. In mathematics, ++ = asserts that the expression on its left is equal to the expression on its right. In C ,= makes the variable on its left take on the value of the expression on its right. It is best to read x = 5 as “x is assigned the value 5,” or “x gets the value 5.” This distinction is important since in mathematics equality is symmetric: ++ if x = 5, we know 5 = x. In C , this symmetry does not exist; the statement 5 = x; attempts to reassign the value of the literal integer value 5, but this cannot be done, because 5 is always 5 and cannot be changed. Such a statement will produce a compiler error: error C2106: ’=’ : left operand must be l-value Variables can be reassigned different values as needed, as Listing 3.5 (multipleassignment.cpp) shows. Listing 3.5: multipleassignment.cpp include iostream int main() int x; x = 10; std::cout x '\n'; x = 20; std::cout x '\n'; x = 30; std::cout x '\n'; ©2017 Richard L. Halterman Draft date: June 2, 2017

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.