My Profile
Active Members
TodayLast 7 Days
more...
Awards & Gifts
Online Exams
Fresher Jobs
Our fresher job section is exclusively for fresh graduates! Find jobs for freshers in major Indian
cities including Bangalore, Chennai, Hyderabad, Pune or Kochi
Resources
Find educational articles, blogs, discussion threads and other resources.
Colleges
Find details about any college in India or search for courses.
Advertisements
|
c Tutorial
Posted Date: 01 May 2008 Resource Type: Articles/Knowledge Sharing Category: E-Books
|
Posted By: sharu Member Level: Gold Rating: Points: 5
|
|
|
|
C LANGUAGE TUTORIAL This tutorial teaches the entire C programming language. It is composed of 13 chapters which should be studied in order since topics are introduced in a logical order and build upon topics introduced in previous chapters. It is to the students benefit to download the source code for the example programs, then compile and execute each program as it is studied. The diligent student will modify the example program in some way, then recompile and execute it to see if he understands the material studied for that program. This will provide the student with valuable experience using his compiler. The recommended method of study is to print the text for one or two chapters, download the example programs, and study the material by loading the example programs in the compiler's editor for viewing. Following successful completion of each chapter, additional chapters can be downloaded as progress is made. Version 2.8 - Sept 8, 1996 - (Files restructured on March 15, 1997) This tutorial is distributed as shareware which means that you do not have to pay to use it. However, the author spent a good deal of time and financial resources to develop this tutorial and requests that you share in the financial burden in a very small way, but only if you felt the tutorial was valuable to you as an aid in learning to program in C. If you wish to remit a small payment to the author, full instructions for doing so will be given by clicking the link below. If you do not wish to remit any payment, please feel free to use the tutorial anyway. In either case, I hope you find programming in C to be rewarding and profitable. I personally think it is an excellent language. How to Remit Payment For this Tutorial! Introduction - What is C and why study it? Chapter 1 - Getting Started Chapter 2 - Program Structure Chapter 3 - Program Control Chapter 4 - Assignment & Logical Compare Chapter 5 - Functions, Variables, & Prototyping Chapter 6 - The C Preprocessor Chapter 7 - Strings and Arrays Chapter 8 - Pointers Chapter 9 - Standard Input/Output Chapter 10 - File Input/Output Chapter 11 - Structures Chapter 12 - Dynamic Allocation Chapter 13 - Character and Bit Manipulation Download the HTML Documentation - (chtm.zip) Download all of the above documents in one packed C Language Tutorial file:///E|/education/C LANGUAGE TUTORIAL/Clist.htm (1 of 2) [4/15/1999 2:45:52 AM] file. This file (about 155k) contains the 14 files listed above (plus the diagrams) which can be downloaded and unpacked for use locally. The content of this file is identical to the content of the above files. There are no executable files in this group of files. Download the Source Code - (csrc.zip) Download all example programs. This file (about 41k) contains 79 source files which are all explained in the 13 chapters of text. There are no executable files in this group of files. Download the Answers to Exercises- (cans.zip) Download the authors answers to all of the programming exercises. This file (about 11k) contains 27 source files. There are no executable files in this group of files. Download the pkunzip executable - (pkunzip.exe) Download pkunzip.exe version 2.04 to unzip the source code. This executable is pre-registered for your use in unzipping any Coronado Enterprises tutorial files. It will unpack and generate the zipped files in the current directory and all will be ASCII source code files. To unzip the source code files, execute the following DOS command; pkunzip csrc.zip Or, to unzip the answers to programming exercises, execute the following DOS command; pkunzip cans.zip Copyright © 1988-1997 Coronado Enterprises - Last update, March 15, 1997 Gordon Dodrill - dodrill@swcp.com - Please email any comments or suggestions. C Language Tutorial file:///E|/education/C LANGUAGE TUTORIAL/Clist.htm (2 of 2) [4/15/1999 2:45:52 AM] Introduction to the C Tutorial C IS USUALLY FIRST The programming language C was originally developed by Dennis Ritchie of Bell Laboratories and was designed to run on a PDP-11 with a UNIX operating system. Although it was originally intended to run under UNIX, there has been a great interest in running it under the MS-DOS operating system on the IBM PC and compatibles. It is an excellent language for this environment because of the simplicity of expression, the compactness of the code, and the wide range of applicability. Also, due to the simplicity and ease of writing a C compiler, it is usually the first high level language available on any new computer, including microcomputers, minicomputers, and mainframes. C is not the best beginning language because it is somewhat cryptic in nature. It allows the programmer a wide range of operations from high level down to a very low level, approaching the level of assembly language. There seems to be no limit to the flexibility available. One experienced C programmer made the statement, "You can program anything in C", and the statement is well supported by my own experience with the language. Along with the resulting freedom however, you take on a great deal of responsibility because it is very easy to write a program that destroys itself due to the silly little errors that a good Pascal compiler will flag and call a fatal error. In C, you are very much on your own as you will soon find. I ASSUME YOU KNOW NOTHING ABOUT C In order to successfully complete this tutorial, you will not need any prior knowlede of the C programming language. I will begin with the most basic concepts of C and take you up to the highest level of C programming including the usually intimidating concepts of pointers, structures, and dynamic allocation. To fully understand these concepts, it will take a good bit of time and work on your part because they are not particularly easy to grasp, but they are very powerful tools. Enough said about that, you will see their power when we get there, just don't allow yourself to worry about them yet. Programming in C is a tremendous asset in those areas where you may want to use Assembly Language but would rather keep it a "simple to write" and "easy to maintain" program. It has been said that a program written in C will pay a premium of a 20 to 50% increase in runtime because no high level language is as compact or as fast as Assembly Language. However, the time saved in coding can be tremendous, making it the most desirable language for many programming chores. In addition, since most programs spend 90 percent of their operating time in only 10 percent or less of the code, it is possible to write a program in C, then rewrite a small portion of the code in Assembly Language and approach the execution speed of the same program if it were written entirely in Assembly Language. Even though the C language enjoys a good record when programs are transported from one implementation to another, there are differences in compilers that you will find anytime you try to use another compiler. Most of the differences become apparent when you use nonstandard extensions such as calls to the DOS BIOS when using MS-DOS, but even these differences can be minimized by careful choice of programming constructs. Throughout this tutorial, every attempt will be made to indicate to you what constructs are available in every C compiler because they are part of the ANSI-C standard, the accepted standard of C C Tutorial - Introduction file:///E|/education/C LANGUAGE TUTORIAL/intro.htm (1 of 3) [4/15/1999 2:46:29 AM] programming. WHAT IS THE ANSI-C STANDARD? When it became evident that the C programming language was becoming a very popular language available on a wide range of computers, a group of concerned individuals met to propose a standard set of rules for the use of the C programming language. The group represented all sectors of the software industry and after many meetings, and many preliminary drafts, they finally wrote an acceptable standard for the C language. It has been accepted by the American National Standards Institute (ANSI), and by the International Standards Organization (ISO). It is not forced upon any group or user, but since it is so widely accepted, it would be economic suicide for any compiler writer to refuse to conform to the standard. YOU MAY NEED A LITTLE HELP Modern C compilers are very capable systems, but due to the tremendous versatility of a C compiler, it could be very difficult for you to learn how to use it effectively. If you are a complete novice to programming, you will probably find the installation instructions somewhat confusing. You may be able to find a colleague or friend that is knowledgeable about computers to aid you in setting up your compiler for initial use. This tutorial cannot cover all aspects of programming in C, simply because there is too much to cover, but it will instruct you in all you need for the majority of your programming in C, and it will introduce essentially all of the C language. You will receive instruction in all of the programming constructs in C, but what must be omitted are methods of programming, since these can only be learned by experience. More importantly, it will teach you the vocabulary of C so that you can go on to more advanced techniques using the programming language C. A diligent effort on your part to study the material presented in this tutorial will result in a solid base of knowledge of the C programming language. You will then be able to intelligently read technical articles or other textbooks on C and greatly expand your knowledge of this modern and very popular programming language. HOW TO USE THIS TUTORIAL This tutorial is written in such a way that the student should sit before his computer and study each example program by displaying it on the monitor and reading the text which corresponds to that program. Following his study of each program, he should then compile and execute it and observe the results of execution with his compiler. This enables the student to gain experience using his compiler while he is learning the C programming language. It is strongly recommended that the student study each example program in the given sequence then write the programs suggested at the end of each chapter in order to gain experience in writing C programs. THIS IS WRITTEN PRIMARILY FOR MS-DOS This tutorial is written primarily for use on an IBM-PC or compatible computer but can be used with any ANSI standard compiler since it conforms so closely to the ANSI standard. In fact, a computer is not even required to study this material since the result of execution of each example program is given in comments at the end of each program. RECOMMENDED READING AND REFERENCE MATERIAL C Tutorial - Introduction file:///E|/education/C LANGUAGE TUTORIAL/intro.htm (2 of 3) [4/15/1999 2:46:29 AM] "The C Programming Language - Second Edition", Brian W. Kernigan & Dennis M. Ritchie, Prentice Hall, 1988 This is the definitive text of the C programming language and is required reading for every serious C programmer. Although the first edition was terse and difficult to read, the second edition is easier to read and extremely useful as both a learning resource and a reference guide. Any ANSI-C textbook Each student should posess a copy of a book that includes a definition of the entire ANSI-C specification and library. Go to a good bookstore and browse for one. Return to Table of Contents Advance to Chapter 1 Copyright © 1988-1997 Coronado Enterprises - Last update, March 15, 1997 Gordon Dodrill - dodrill@swcp.com - Please email any comments or suggestions. C Tutorial - Introduction file:///E|/education/C LANGUAGE TUTORIAL/intro.htm (3 of 3) [4/15/1999 2:46:29 AM] C Tutorial - Chapter 1 GETTING STARTED WHAT IS AN IDENTIFIER? Before you can do anything in any language, you must know how to name an identifier. An identifier is used for any variable, function, data definition, etc. In the C programming language, an identifier is a combination of alphanumeric characters, the first being a letter of the alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit, or the underline. Two rules must be kept in mind when naming identifiers. The case of alphabetic characters is significant. Using INDEX for a variable name is not the same as using index and neither of them is the same as using InDeX for a variable name. All three refer to different variables. 1. According to the ANSI-C standard, at least 31 significant characters can be used and will be considered significant by a conforming ANSI-C compiler. If more than 31 are used, all characters beyond the 31st may be ignored by any given compiler. 2. WHAT ABOUT THE UNDERLINE? The underline can be used as part of a variable name, and adds greatly to the readability of the resulting code. It is used by some, but not all, experienced C programmers. A few underlines are used for illustration in this tutorial. Since most compiler writers use the underline as the first character for variable names internal to the system, you should refrain from using the underline to begin an identifier to avoid the possibility of a name clash. To get specific, identifiers with two leading underscores are reserved for the compiler as well as identifiers beginning with a single underscore and using an upper case alphabetic character for the second. If you make it a point of style to never use an identifier with a leading underline, you will not have a naming clash with the system. It adds greatly to the readability of a program to use descriptive names for variables and it would be to your advantage to do so. Pascal and Ada programmers tend to use long descriptive names, but most C programmers tend to use short cryptic names. Most of the example programs in this tutorial use very short names for that reason, but a few longer names are used for illustrative purposes. KEYWORDS There are 32 words defined as keywords in C. These have predefined uses and cannot be used for any other purpose in a C program. They are used by the compiler as an aid to compiling the program. They are always written in lower case. A complete list follows; 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 C Tutorial - Chapter 1 file:///E|/education/C LANGUAGE TUTORIAL/chap01.htm (1 of 3) [4/15/1999 2:46:47 AM] do if static while In addition to this list of keywords, your compiler may define a few more. If it does, they will be listed in the documentation that came with your compiler. Each of the above keywords will be defined, illustrated, and used in this tutorial. WE NEED DATA AND A PROGRAM Any computer program has two entities to consider, the data, and the program. They are highly dependent on one another and careful planning of both will lead to a well planned and well written program. Unfortunately, it is not possible to study either completely without a good working knowledge of the other. For that reason, this tutorial will jump back and forth between teaching methods of program writing and methods of data definition. Simply follow along and you will have a good understanding of both. Keep in mind that, even though it seems expedient to sometimes jump right into coding the program, time spent planning the data structures will be well spent and the quality of the final program will reflect the original planning. HOW THIS TUTORIAL IS WRITTEN As you go through the example programs, you will find that every program is complete. There are no program fragments that could be confusing. This allows you to see every requirement that is needed to use any of the features of C as they are presented. Some tutorials I have seen give very few, and very complex examples. They really serve more to confuse the student. This tutorial is the complete opposite because it strives to cover each new aspect of programming in as simple a context as possible. Throughout this tutorial, keywords, variable names, and function names will be given in boldface as an aid to clarity. These terms will be completely defined throughout the tutorial. RESULT OF EXECUTION The result of executing each program will be given in comments at the end of the program listing after the comment is defined in about the fourth program of chapter 2. If you feel confident that you completely understand the program, you can simply refer to the result of execution to see if you understand the result. In this case, it will not be necessary for you to compile and execute every program. It would be a good exercise for you to compile and execute some of them however, because all C compilers will not generate exactly the same results and you need to get familiar with your own compiler. Example program ------> FIRSTEX.C At this point, you should compile and execute FIRSTEX.C if you have not yet done so, to see that your C compiler is properly loaded and operating. Don't worry about what the program does yet. In due time you will understand it completely. Note that this program will compile and execute properly with any good compiler. A WORD ABOUT COMPILERS All of the example programs in this tutorial will compile and execute correctly with any good ANSI compatible C compiler. Some compilers have gotten extremely complex and hard to use for a beginning C Tutorial - Chapter 1 file:///E|/education/C LANGUAGE TUTORIAL/chap01.htm (2 of 3) [4/15/1999 2:46:47 AM] C programmer, and some only compile and build Microsoft Windows programs. Fortunately, most of the C compilers available have a means of compiling a standard C program which is written for the DOS environment and includes none of the Windows extensions. You should check your documentation for the capabilities and limitations of your compiler. If you have not yet purchased a C compiler, you should find one that is ANSI-C compliant, and that also has the ability to generate a DOS executable if you are planning to use the DOS operating system. ANSWERS TO PROGRAMMING EXERCISES There are programming exercises at the end of most of the chapters. You should attempt to do original work on each of the exercises before referring to the answers (all of which are zipped into cans.zip) in order to gain your own programming experience. These answers are given for your information in case you are completely stuck on how to solve a particular problem. These answers are not meant to be the only answer, since there are many ways to program anything, but they are meant to illustrate one way to solve the suggested programming problem. The answers are all in source files named in the format CHnn_m.C where nn is the chapter number, and m is the exercise number. If more than one answer is required, an A, B, or C is included following the exercise number. Return to Table of Contents Advance to Chapter 2 Copyright © 1988-1997 Coronado Enterprises - Last update, March 15, 1997 Gordon Dodrill - dodrill@swcp.com - Please email any comments or suggestions. C Tutorial - Chapter 1 file:///E|/education/C LANGUAGE TUTORIAL/chap01.htm (3 of 3) [4/15/1999 2:46:47 AM] C Tutorial - Chapter 2 GETTING STARTED IN C YOUR FIRST C PROGRAM Example program ------> TRIVIAL.C The best way to get started with C is to actually study a program, so load the file named TRIVIAL.C and display it on the monitor. You are looking at the simplest possible C program. There is no way to simplify this program or to leave anything out. Unfortunately, the program doesn't do anything. The word main is very important, and must appear once, and only once in every C program. This is the point where execution is begun when the program is run. We will see later that this does not have to be the first statement in the program but it must exist as the entry point. Following the main program name is a pair of parentheses which are an indication to the compiler that this is a function. We will cover exactly what a function is in due time. For now, I suggest that you simply include the pair of parentheses. The two curly brackets in lines 2 and 3, properly called braces, are used to define the limits of the program itself. The actual program statements go between the two braces and in this case, there are no statements because the program does absolutely nothing. You can compile and run this program, but since it has no executable statements, it does nothing. Keep in mind, however, that it is a valid C program. When you compile this program, you may get a warning. You can ignore the warning and we will discuss it later in this tutorial, or you can modify the program so that it appears as follows; int main() { return 0; } This modified program must compile on any good C compiler since it conforms to the ANSI-C standard. We will explain the difference in these two programs later in this tutorial. A PROGRAM THAT DOES SOMETHING Example program ------> WRTSOME.C For a much more interesting program, load the program named WRTSOME.C and display it on your monitor. It is the same as the previous program except that it has one executable statement between the braces plus the obligatory return statement. The executable statement is a call to a function supplied as a part of your C library. Once again, we will not worry about what a function is, but only how to use this one named printf(). In order to output text to the monitor, the desired text is put within the function parentheses and bounded by quotation marks. The end result is that whatever text is included between the quotation marks will be displayed on the monitor when the program is run. Notice the semi-colon at the end of line 5. C uses a semi-colon as a statement terminator, so the semi-colon is required as a signal to the compiler that this line is complete. This program is also C Tutorial - Chapter 2 file:///E|/education/C LANGUAGE TUTORIAL/chap02.htm (1 of 5) [4/15/1999 2:47:00 AM] executable, so you can compile and run it to see if it does what you think it should. It should cause the text between the quotation marks to appear on the monitor when you execute it. You can ignore the statements in lines 1 and 7 in this program and similar statements in each of the remaining programs in this chapter. These will be fully described later in this tutorial. We will also define why the word int is used at the begining of line 3. We have a few preliminary topics to cover before we get to these items. ANOTHER PROGRAM WITH MORE OUTPUT Example program ------> WRTMORE.C Load the program WRTMORE.C and display it on your monitor for an example with more output and another small but important concept. You will see that there are four executable statements in this program, each one being a call to the function printf(). The top line will be executed first, then the next, and so on, until the fourth line is complete. The statements are executed sequentially from top to bottom. Notice the funny character near the end of the first line, namely the backslash. The backslash is used in the printf() statement to indicate that a special control character is following. In this case, the "n" indicates that a newline is requested. This is an indication to return the cursor to the left side of the monitor and move down one line. Any place within printed text that you desire, you can put a newline character to start a new line. You could even put it in the middle of a word and split the word between two lines. A complete description of this program is now possible. The first printf() outputs a line of text and returns the carriage. (Of course, there is no carriage, but the cursor is moved to the next line on the monitor. The terminology carries over from the days of teletypes.) The second printf() outputs a line of text but does not return the carriage so that the third line is appended to the end of the second, then followed by two carriage returns, resulting in a blank line. Finally the fourth printf() outputs a line followed by a carriage return and the program is complete. After compiling and executing WRTMORE.C, the following text should be displayed on your monitor; This is a line of text to output. And this is another line of text. This is a third line. Compile and execute this program to see if it gives you this output. It would be a good idea at this time for you to experiment by adding additional lines of printout to see if you understand how the statements really work. Add a few carriage returns in the middle of a line to prove to yourself that it works as stated, then compile and execute the modified program. The more you modify and compile the example programs included with this tutorial, the more you will learn as you work your way through it. LET'S PRINT SOME NUMBERS Example program ------> ONEINT.C Load the file named ONEINT.C and display it on the monitor for our first example of how to work with data in a C program. The entry point main() should be clear to you by now as well as the beginning C Tutorial - Chapter 2 file:///E|/education/C LANGUAGE TUTORIAL/chap02.htm (2 of 5) [4/15/1999 2:47:00 AM] brace. The first new thing we encounter is line 5 containing int index; which is used to define an integer variable named index. The word int is a keyword in C, and can not be used for anything else. It defines a variable that can store a whole number within a predefined range of values. We will define an actual range later. The variable name, index, can be any name that follows the rules for an identifier and is not one of the keywords for C. The final character on the line, the semi-colon, is the statement terminator as discussed earlier. Note that, even though we have defined a variable, we have not yet assigned a value to it, so it contains an undefined value. We will see in a later chapter that additional integers could also be defined on the same line, but we will not complicate the present situation. Observing the main body of the program, you will notice that there are three statements that assign a value to the variable index, but only one at a time. The statement in line 7 assigns the value of 13 to index, and its value is printed out by line 8. (We will see how shortly. Trust me for the time being.) Later, the value of 27 is assigned to index, and finally 10 is assigned to it, each value being printed out. It should be intuitively clear that index is indeed a variable and can store many different values but only one value at a time of course. Please note that many times the words "printed out" are used to mean "displayed on the monitor". You will find that in many cases experienced programmers take this liberty, probably due to the printf() function being used for monitor display. HOW DO WE PRINT NUMBERS? To keep our promise, let's return to the printf() statements for a definition of how they work. Notice that they are all identical and that they all begin just like the printf() statements we have seen before. The first difference occurs when we come to the % character. This is a special character that signals the output routine to stop copying characters to the output and do something different, usually to output the value of a variable. The % sign is used to signal the output of many different types of variables, but we will restrict ourselves to only one for this example. The character following the % sign is a d, which signals the output routine to get a decimal value and output it. Where the decimal value comes from will be covered shortly. After the d, we find the familiar \n, which is a signal to return the video "carriage", and the closing quotation mark. All of the characters between the quotation marks define the pattern of data to be output by this statement. Following the output pattern, there is a comma followed by the variable name index. This is where the printf() statement gets the decimal value which it will output because of the %d we saw earlier. The system substitutes the current value of the variable named index for the %d and copies it to the monitor. We could add more %d output field descriptors anywhere within the brackets and more variables following the description to cause more data to be printed with one statement. Keep in mind however, that the number of field descriptors and the number of variable definitions must be the same or the runtime system will generate something we are not expecting. Much more will be covered at a later time on all aspects of input and output formatting. A reasonably good grasp of these fundamentals are necessary in order to understand the following lessons. It is not necessary to understand everything about output formatting at this time, only a fair understanding of the basics. C Tutorial - Chapter 2 file:///E|/education/C LANGUAGE TUTORIAL/chap02.htm (3 of 5) [4/15/1999 2:47:00 AM] Compile and run ONEINT.C and observe the output. Two programming exercises at the end of this chapter are based on this program. HOW DO WE ADD COMMENTS IN C? Example program ------> COMMENTS.C Load the file named COMMENTS.C and observe it on your monitor for an example of how comments can be added to a C program. Comments are added to make a program more readable to you but represent nonsense to the compiler, so we must tell the compiler to ignore the comments completely by bracketing them with special characters. The slash star combination is used in C for comment delimiters, and are illustrated in the program at hand. Please note that the program does not illustrate good commenting practice, but is intended to illustrate where comments can go in a program. It is a very sloppy looking program. The slash star combination in line 3 introduces the first comment and the star slash at the end of that line terminates this comment. Note that this comment is prior to the beginning of the program illustrating that a comment can precede the program itself. Good programming practice would include a comment prior to the program with a short introductory description of the program. The comment in line 5 is after the main program entry point and prior to the opening brace for the program code itself. The third comment starts after the first executable statement in line 7 and continues for four lines. This is perfectly legal because a comment can continue for as many lines as desired until it is terminated. Note carefully that if anything were included in the blank spaces to the left of the three continuation lines of the comment, it would be part of the comment and would not be compiled, but totally ignored by the compiler. The last comment, in line 15, is located following the completion of the program, illustrating that comments can go nearly anywhere in a C program. Experiment with this program by adding comments in other places to see what will happen. Comment out one of the printf() statements by putting comment delimiters both before and after it and see that it does not get executed and therefore does not produce a line of printout. Comments are very important in any programming language because you will soon forget what you did and why you did it. It will be much easier to modify or fix a well commented program a year from now than one with few or no comments. You will very quickly develop your own personal style of commenting. Some C compilers will allow you to "nest" comments which can be very handy if you need to "comment out" a section of code during debugging. Since nested comments are not a part of the ANSI-C standard, none will be used in this tutorial. Check the documentation for your compiler to see if they are permitted with your implementation of C. Even though they may be allowed, it is a good idea to refrain from their use, since they are rarely used by experienced C programmers, and using them may make it difficult to port your code to another compiler if the need should arise. GOOD FORMATTING STYLE Example program ------> GOODFORM.C Load the file GOODFORM.C and observe it on your monitor. It is an example of a well formatted program. Even though it is very short and therefore does very little, it is very easy to see at a glance what C Tutorial - Chapter 2 file:///E|/education/C LANGUAGE TUTORIAL/chap02.htm (4 of 5) [4/15/1999 2:47:00 AM] it does. With the experience you have already gained in this tutorial, you should be able to very quickly grasp the meaning of the program in it's entirety. Your C compiler ignores all extra spaces and all carriage returns giving you considerable freedom in formatting your program. Indenting and adding spaces is entirely up to you and is a matter of personal taste. Compile and run the program to see if it does what you expect it to do. Example program ------> UGLYFORM.C Now load and display the program UGLYFORM.C and observe it. How long will it take you to figure out what this program will do? It doesn't matter to the compiler which format style you use, but it will matter to you when you try to debug your program. Compile this program and run it. You may be surprised to find that it is the same program as the last one, except for the formatting. Don't get too worried about formatting style yet. You will have plenty of time to develop a style of your own as you learn the C language. Be observant of styles as you see C programs in magazines and books. This covers some of the basic concepts of programming in C, but as there are many other things to learn, we will forge ahead to additional program structure. It will definitely be to your advantage to do the programming exercises at the end of each chapter. They are designed to augment your studies and teach you to use your compiler. PROGRAMMING EXERCISES 1. Write a program to display your name on the monitor. Modify the program to display your address and phone number on separate lines by adding two additional printf() statements. 2. Remove line 7 from ONEINT.C by commenting it out, then compile and execute the resulting program to see the value of an uninitialized variable. This can be any value within the allowable range for that variable. If it happens to have the value of zero, that is only a coincidence, but then zero is the most probable value to be in an uninitialized variable because there are lots of zero values floating around in a computer's memory. It is actually legal for the program to abort if you refer to a variable that you failed to initialize, but few compilers, if any, will actually do so. 3. Add the following two lines just after the last printf() of ONEINT.C to see what it does. Study it long enough to completely understand the result. 4. printf("Index is %d\n it still is %d\n it is %d", index, index, index); Return to Table of Contents Advance to Chapter 3 Copyright © 1988-1997 Coronado Enterprises - Last update, March 15, 1997 Gordon Dodrill - dodrill@swcp.com - Please email any comments or suggestions. C Tutorial - Chapter 2 file:///E|/education/C LANGUAGE TUTORIAL/chap02.htm (5 of 5) [4/15/1999 2:47:00 AM] C Tutorial - Chapter 3 PROGRAM CONTROL THE WHILE LOOP The C programming language has several structures for looping and conditional branching. We will cover them all in this chapter and we will begin with the while loop. The while loop continues to loop while some condition is true. When the condition becomes false, the looping is discontinued. It therefore does just what it says it does, the name of the loop being very descriptive. Example program ------> WHILE.C Load the program WHILE.C and display it for an example of a while loop. We begin with a comment and the program entry point main(), then go on to define an integer variable named count within the body of the program. The variable is set to zero and we come to the while loop itself. The syntax of a while loop is just as shown here. The keyword while is followed by an expression of something in parentheses, followed by a compound statement bracketed by braces. As long as the expression in the parenthesis is true, all statements within the braces will be repeatedly executed. In this case, since the variable count is incremented by one every time the statements are executed, it will eventually reach 6. At that time the statement will not be executed because count is not less than 6, and the loop will be terminated. The program control will resume at the statement following the statements in braces. We will cover the compare expression, the one in parentheses, in the next chapter. Until then, simply accept the expressions for what you think they should do and you will be correct for these simple cases. Several things must be pointed out regarding the while loop. First, if the variable count were initially set to any number greater than 5, the statements within the loop would not be executed at all, so it is possible to have a while loop that never is executed. Secondly, if the variable were not incremented in the loop, then in this case, the loop would never terminate, and the program would never complete. Finally, if there is only one statement to be executed within the loop, it does not need delimiting braces but can stand alone. Compile and run this program after you have studied it enough to assure yourself that you understand its operation completely. Note that the result of execution is given for this program, (and will be given for all of the remaining example programs in this tutorial) so you do not need to compile and execute every program to see the results. Be sure to compile and execute some of the programs however, to gain experience with your compiler. You should make some modifications to any programs that are not completely clear to you and compile them until you understand them completely. The best way to learn is to try various modifications yourself. We will continue to ignore the #include statement and the return statement in the example programs in this chapter. We will define them completely later in this tutorial. THE DO-WHILE LOOP C Tutorial - Chapter 3 file:///E|/education/C LANGUAGE TUTORIAL/chap03.htm (1 of 6) [4/15/1999 2:47:20 AM] Example program ------> DOWHILE.C A variation of the while loop is illustrated in the program DOWHILE.C, which you should load and display. This program is nearly identical to the last one except that the loop begins with the keyword do, followed by a compound statement in braces, then the keyword while, and finally an expression in parentheses. The statements in the braces are executed repeatedly as long as the expression in the parentheses is true. When the expression in parentheses becomes false, execution is terminated, and control passes to the statements following this statement. Several things must be pointed out regarding the do-while loop. Since the test is done at the end of the loop, the statements in the braces will always be executed at least once. Secondly, if the variable i were not changed within the loop, the loop would never terminate, and hence the program would never terminate. It should come as no surprise to you that these loops can be nested. That is, one loop can be included within the compound statement of another loop, and the nesting level has no limit. This will be illustrated later. Compile and run this program to see if it does what you think it should do. THE FOR LOOP Example program ------> FORLOOP.C Load and display the file named FORLOOP.C on your monitor for an example of a program with a for loop. The for loop consists of the keyword for followed by a rather large expression in parentheses. This expression is really composed of three fields separated by semi-colons. The first field contains the expression "index = 0" and is an initializing field. Any expressions in this field are executed prior to the first pass through the loop. There is essentially no limit as to what can go here, but good programming practice would require it to be kept simple. Several initializing statements can be placed in this field, separated by commas. The second field, in this case containing "index < 6", is the test which is done at the beginning of each pass through the loop. It can be any expression which will evaluate to a true or false. (More will be said about the actual value of true and false in the next chapter.) The expression contained in the third field is executed each time the loop is exercised but it is not executed until after those statements in the main body of the loop are executed. This field, like the first, can also be composed of several operations separated by commas. Following the for() expression is any single or compound statement which will be executed as the body of the loop. A compound statement is any group of valid C statements enclosed in braces. In nearly any context in C, a simple statement can be replaced by a compound statement that will be treated as if it were a single statement as far as program control goes. Compile and run this program. The while is convenient to use for a loop when you don't have any idea how many times the loop will be executed, and the for loop is usually used in those cases when you are doing a fixed number of iterations. The for loop is also convenient because it moves all of the control information for a loop into one place, between the parentheses, rather than at both ends of the code. It is your choice as to which you would rather use. Depending on how they are used, it is possible with each of these two loops to never execute C Tutorial - Chapter 3 file:///E|/education/C LANGUAGE TUTORIAL/chap03.htm (2 of 6) [4/15/1999 2:47:20 AM] the code within the loop at all. This is because the test is done at the beginning of the loop, and the test may fail during the first iteration. The do-while loop however, due to the fact that the code within the loop is executed prior to the test, will always execute the code at least once. THE IF STATEMENT Example program ------> IFELSE.C Load and display the file IFELSE.C for an example of our first conditional branching statement, the if. Notice first, that there is a for loop with a compound statement as its executable part containing two if statements. This is an example of how statements can be nested. It should be clear to you that each of the if statements will be executed 10 times. Consider the first if statement. It starts with the keyword if followed by an expression in parentheses. If the expression is evaluated and found to be true, the single statement following the if is executed, and if false, the following statement is skipped. Here too, the single statement can be replaced by a compound statement composed of several statements bounded by braces. The expression "data == 2" is simply asking if the value of data is equal to 2. This will be explained in detail in the next chapter. (Simply suffice for now that if "data = 2" were used in this context, it would mean a completely different thing. You must use the double equal sign for comparing values.) NOW FOR THE IF-ELSE The second if is similar to the first with the addition of a new keyword, the else in line 17. This simply says that if the expression in the parentheses evaluates as true, the first expression is executed, otherwise the expression following the else is executed. Thus, one of the two expressions will always be executed, whereas in the first example the single expression was either executed or skipped. Both will find many uses in your C programming efforts. Compile and run this program to see if it does what you expect. THE BREAK AND CONTINUE Example program ------> BREAKCON.C Load the file named BREAKCON.C for an example of two new statements. Notice that in the first for loop, there is an if statement that calls a break if xx equals 8. The break will jump out of the loop you are in and begin executing statements immediately following the loop, effectively terminating the loop. This is a valuable statement when you need to jump out of a loop depending on the value of some results calculated in the loop. In this case, when xx reaches the value of 8, the loop is terminated and the last value printed will be the previous value, namely 7. The break always jumps out of the loop just past the terminating brace. The next for loop starting in line 15, contains a continue statement which does not cause termination of the loop but jumps out of the present iteration. When the value of xx reaches 8 in this case, the program will jump to the end of the loop and continue executing the loop, effectively eliminating the printf() statement during the pass through the loop when xx is eight. The continue statement always jumps to the end of the loop just prior to the terminating brace. At that time the loop is terminated or continues based on the result of the loop test. Be sure to compile and execute this program. C Tutorial - Chapter 3 file:///E|/education/C LANGUAGE TUTORIAL/chap03.htm (3 of 6) [4/15/1999 2:47:20 AM] THE SWITCH STATEMENT Example program ------> SWITCH.C Load and display the file SWITCH.C for an example of the biggest construct yet in the C language, the switch. The switch is not difficult, so don't let it intimidate you. It begins with the keyword switch followed by a variable in parentheses which is the switching variable, in this case truck. As many cases as needed are then enclosed within a pair of braces. The reserved word case is used to begin each case, followed by the value of the variable for that case, then a colon, and the statements to be executed. In this example, if the variable named truck contains the value 3 during this pass of the switch statement, the printf() in line 13 will cause "The value is three\n" to be displayed, and the break statement will cause us to jump out of the switch. The break statement here works in much the same manner as the loop, it jumps out just past the closing brace. Once an entry point is found, statements will be executed until a break is found or until the program drops through the bottom of the switch braces. If the variable truck has the value 5, the statements will begin executing at line 17 where "case 5 :" is found, but the first statements found are where the case 8 statements are. These are executed and the break statement in line 21 will direct the execution out of the bottom of the switch just past the closing brace. The various case values can be in any order and if a value is not found, the default portion of the switch will be executed. It should be clear that any of the above constructs can be nested within each other or placed in succession, depending on the needs of the particular programming project at hand. Note that the switch is not used as frequently as the loop and the if statements. In fact, the switch is used infrequently but should be completely understood by the serious C programmer. Be sure to compile and run SWITCH.C and examine the results. THE EVIL GOTO STATEMENT Example program ------> GOTOEX.C Load and display the file GOTOEX.C for an example of a file with some goto statements in it. To use a goto statement, you simply use the reserved word goto followed by the symbolic name to which you wish to jump. The name is then placed anywhere in the program followed by a colon. You can jump nearly anywhere within a function, but you are not permitted to jump into a loop, although you are allowed to jump out of a loop. This particular program is really a mess but it is a good example of why software writers are trying to eliminate the use of the goto statement as much as possible. The only place in this program where it is reasonable to use the goto is the one in line 23 where the program jumps out of the three nested loops in one jump. In this case it would be rather messy to set up a variable and jump successively out of each of the three nested loops but one goto statement gets you out of all three in a very concise manner. Some persons say the goto statement should never be used under any circumstances, but this is narrow minded thinking. If there is a place where a goto will clearly do a neater control flow than some other construct, feel free to use it. It should not be abused however, as it is in the rest of the program on your monitor. Entire books are written on "gotoless" programming, better known as Structured Programming. C Tutorial - Chapter 3 file:///E|/education/C LANGUAGE TUTORIAL/chap03.htm (4 of 6) [4/15/1999 2:47:20 AM] Compile and run GOTOEX.C and study its output. It would be a good exercise to rewrite it and see how much more readable it is when the statements are listed in order. FINALLY, A MEANINGFUL PROGRAM Example program ------> TEMPCONV.C Load the file named TEMPCONV.C for an example of a useful, even though somewhat limited program. This is a program that generates a list of centigrade and fahrenheit temperatures and prints a message out at the freezing point of water and another at the boiling point of water. Of particular importance is the formatting. The header is several lines of comments describing what the program does in a manner that catches the readers attention and is still pleasing to the eye. You will eventually develop your own formatting style, but this is a good way to start. Also if you observe the for loop, you will notice that all of the contents of the compound statement are indented 3 spaces to the right of the for keyword, and the opening and closing braces are lined up under the "f" in for. This makes debugging a bit easier because the construction becomes very obvious. (The next example program will illustrate two additional methods of formatting braces.) You will also notice that the printf() statements that are in the if statements within the big for loop are indented three additional spaces because they are part of yet another construct. This is the first program in which we used more than one variable. The three variables are simply defined on three different lines and are used in the same manner as a single variable was used in previous programs. By defining them on different lines, we have an opportunity to define each with a comment. It would be possible to define them on one line, but to do so would remove the ability to include a comment on each line. This is illustrated in the next program. Be sure to compile and execute the current program. ANOTHER POOR PROGRAMMING EXAMPLE Example program ------> DUMBCONV.C Recalling UGLYFORM.C from the last chapter, you saw a very poorly formatted program. If you load and display DUMBCONV.C you will have an example of poor formatting which is much closer to what you will find in practice. This is the same program as TEMPCONV.C with the comments removed and the variable names changed to remove the descriptive aspect of the names. Although this program does exactly the same as the last one, it is much more difficult to read and understand. You should begin to develop good programming practices now by studying this program to learn what not to do. It would be beneficial for you to remove the indentation from the last two example programs to see how much more difficult it is to understand the structure of the program without the indentations. OUR FIRST STYLE PROGRAM Example program ------> STYLE1.C This program does nothing practical except to illustrate various styles of formatting and how to combine some of the constructs introduced in this chapter. There is nothing in this program that we have not studied so far in this tutorial. The program is heavily commented and should be studied in detail by the C Tutorial - Chapter 3 file:///E|/education/C LANGUAGE TUTORIAL/chap03.htm (5 of 6) [4/15/1999 2:47:20 AM] diligent C student to begin learning proper C programming style. Like all other example programs, this one can be compiled and executed, and should be. PROGRAMMING EXERCISES Write a program that writes your name on the monitor ten times. Write this program three times, once with each looping method. 1. Write a program that counts from one to ten, prints the values on a separate line for each, and includes a message of your choice when the count is 3 and a different message when the count is 7. 2. Return to Table of Contents Advance to Chapter 4 Copyright © 1988-1997 Coronado Enterprises - Last update, March 15, 1997 Gordon Dodrill - dodrill@swcp.com - Please email any comments or suggestions. C Tutorial - Chapter 3 file:///E|/education/C LANGUAGE TUTORIAL/chap03.htm (6 of 6) [4/15/1999 2:47:20 AM] C Tutorial - Chapter 4 ASSIGNMENT & LOGICAL COMPARES Throughout this chapter, references are given to various ranges of variables. This refers to the range of values that can be stored in any given variable. Your compiler may use a different range for some of the variables since the ANSI standard does not define specific limits for all data types. Consult the documentation for your compiler for the exact range of each of the variable types. INTEGER ASSIGNMENT STATEMENTS Example program ------> INTASIGN.C Load the file named INTASIGN.C and display it for an example of assignment statements. Three variables are defined for use in the program and the remainder of the program is merely a series of illustrations of various kinds of assignment statements. All three variables are defined on one line and have unknown values stored in them initially. The first two lines of the assignment statements, lines 8 and 10, assign numerical values to the variables named a and b, and the next five lines illustrate the five basic arithmetic functions and how to use them. The fifth is the modulo operator and gives the remainder if the two variables were divided. It can only be applied to integral type variables, which will be defined later. Lines 15 and 16 illustrate how to combine some of the variables in relatively complex math expressions. All of the above examples should require no comment except to say that none of the equations are meant to be particularly useful except as illustrations. Precedence of operators is a very important topic that you will need to study in detail at some point, but for now we will only need a few rules. When you have mixed arithmetic expressions, the multiplication and division operations are completed before the addition and subtraction operations when they are all at the same logical level. Therefore when evaluating a * b + c / d, the multiplication and division are done first, then the addition is performed. However in the expression a * (b + c / d), the addition follows the division, but preceeds the multiplication because the operations are at two different logical levels as defined by the parentheses. The expressions in lines 17 and 18 are perfectly acceptable as given, but we will see later in this chapter that there is another way to write these for more compact code. VERY STRANGE LOOKING CODE This brings us to lines 20 and 21 which may appear to you as being very strange. The C compiler scans the assignment statement from right to left, (which may seem a bit odd since we do not read that way), resulting in a very useful construct, namely the one given here. The compiler finds the value 20, assigns it to c, then continues to the left finding that the latest result of a calculation should be assigned to b. Thinking that the latest calculation resulted in a 20, it assigns that value to b also, and continues the leftward scan assigning the value 20 to a also. This is a very useful construct when you are initializing a group of variables. The statement in line 21 illustrates that it is possible to actually do some calculations to arrive at the value which will be assigned to all three variables. The values of a, b, and c, prior to the beginning of the statement in line 21 are used to calculate a value, which is then assigned to each of the C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (1 of 12) [4/15/1999 2:47:33 AM] three variables. As an aid to understanding, line 23 is given which contains parentheses to group the terms together in a meaningful way. Lines 20 and 23 are identical statements. The program has no output, so compiling and executing this program will be very uninteresting. Since you have already learned how to display some integer results using the printf() function, it would be to your advantage to add some output statements to this program to see if the various statements do what you think they should do. You will need to add #include to the beginning of the program if you are going to add printf() statements to the program. You can add your own assignment statements also to gain experience with them. DEFINITIONS FIRST THEN EXECUTABLE STATEMENTS This would be a good time for a preliminary definition of a rule to be followed in C. The variable definitions are always given before any executable statements in any program block. This is why the variables are defined at the beginning of a block in this program and in every C program. If you try to define a new variable after some executable statements, your compiler will issue an error. A program block is any unit of one or more statements surrounded by braces. Actually, the block can even be empty but then there is no real need for it, except as a placeholder in early phases of code development. More will be said about blocks later. ADDITIONAL DATA TYPES Example program ------> MORTYPES.C Loading and editing MORTYPES.C will illustrate how some additional data types can be used. Once again we have defined a few integer type variables which you should be fairly familiar with by now, but we have added two new types, the char, and the float. The char type of data is nearly the same as the integer except that it can only be assigned numerical values between -128 and 127 on most microcomputer implementations of C, since it is usually stored in one byte of memory. Some implementations of C use a larger memory element for a char and will therefore cover a wider range of usable values. The char type of data is usually used for ASCII data, more commonly known as text. The text you are reading was originally written on a computer with a word processor that stored the words in the computer one character per byte. In contrast, the int data type is stored in two bytes of computer memory on nearly all microcomputers, but can be larger on some machines. In fact, most modern microcomputers are 32 bit machines that store an int in four bytes. Keep in mind that, even though the char type variable was designed to hold a representation of an ASCII character, it can be used very effectively to store a very small value if desired. Much more will be discussed on this topic in chapter 7 when we discuss strings. DATA TYPE MIXING It would be profitable at this time to discuss the way C handles the two types char and int. Most operations in C that are designed to operate with integer type variables will work equally well with character type variables because they are an integral variable, which means that they have no fractional part. Those operations, when called on to use a char type variable, will actually promote the char data C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (2 of 12) [4/15/1999 2:47:33 AM] into integer data before using it. For this reason, it is possible to mix char and int type variables in nearly any way you desire. The compiler will not get confused, but you might. It is good not to rely on this too much, but to carefully use only the proper types of data where they should be used. The second new data type is the float type of data, commonly called floating point data. This is a data type which usually has a very large range, a relatively large number of significant digits, and a large number of computer words are required to store it. The float data type has a decimal point associated with it and several bytes of memory are required to store a single float type variable. HOW TO USE THE NEW DATA TYPES The first three lines of the program assign values to all nine of the defined variables so we can manipulate some of the data between the different types. Since, as mentioned above, a char data type is in reality an integral data type which is automatically promoted to int when necessary, no special considerations need be taken to promote a char to an int, and a char type data field can be assigned to an int variable. When going the other way, an int type variable can be assigned to a char type variable and will translate correctly to a char type variable if the value is within the range of the char, possibly -128 to 127. If the value is outside of the range of char, most C compilers simply truncate the most significant bits and use the least significant bits. Line 16 illustrates the simplicity of translating an int into a float. Simply assign it the new value and the system will do the proper conversion. When converting from float to int however, there is an added complication. Since there may be a fractional part of the floating point number, the system must decide what to do with it. By definition, it will truncate it and throw away the fractional part. This program produces no output, and we haven't covered a way to print out char and float type variables, so you can't really get in to this program and play with the results. The next program will cover these topics for you. Be sure to compile and run this program after you are sure you understand it completely. Note that the compiler may issue warnings about type conversions when compiling this program. They can be ignored because of the small values we are using to illustrate the various type conversions. SOME TYPICAL SIZES This list gives you some typical values for the various types available in C. Your compiler may offer different limits and sizes since there is a lot of latitude in what a compiler may offer. The values in this list are for Microsoft Visual C++ version 1.5 (16 bits) and Visual C++ version 2.0 (32 bits). Type Name Bytes Range ------------- 16 bit system ------------- char 1 -128 to 127 signed char 1 -128 to 127 unsigned char 1 0 to 255 short 2 -32,768 to 32,767 unsigned short 2 0 to 65,535 int 2 -32,768 to 32,767 unsigned int 2 0 to 65,535 long 4 -2,147,483,648 to 2,147,483,647 C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (3 of 12) [4/15/1999 2:47:34 AM] unsigned long 4 0 to 4,294,967,295 float 4 3.4E+/-38 (7 digits) double 8 1.7E+/-308 (15 digits) long double 10 1.2E+/-4932 (19 digits) ------------- 32 bit system ------------- char 1 -128 to 127 signed char 1 -128 to 127 unsigned char 1 0 to 255 short 2 -32,768 to 32,767 unsigned short 2 0 to 65,535 int 4 -2,147,483,648 to 2,147,483,647 unsigned int 4 0 to 4,294,967,295 long 4 -2,147,483,648 to 2,147,483,647 unsigned long 4 0 to 4,294,967,295 float 4 3.4E+/-38 (7 digits) double 8 1.7E+/-308 (15 digits) long double 10 1.2E+/-4932 (19 digits) The diligent student will notice that the only difference in these two lists are in the sizes and ranges of the int type variables, both signed and unsigned. The ANSI-C standard says that an int type has the "natural size suggested by the architecture of the execution environment", so the ranges for the compiler listed above matches the standard exactly. One other point about the above table must be made at this time. The unadorned char is permitted to be either signed or unsigned at the discretion of the compiler writer. The writers of the Microsoft compiler chose to make char default to a signed char, as do most compiler writers, but you have a choice since most compilers provide a switch to select the default to unsigned char. Some useful constants are available for your use in determining the range limits of the standard types. For example, the names INT_MIN and INT_MAX are available in the file "limits.h" as constants which can be used in your code. INT_MAX is the largest possible number that can be stored in an int type variable using the compiler that you are currently using. When you switch to a new compiler, which you will almost certainly do someday, INT_MAX will refer to the largest value that can be stored with that compiler. Even if you switch to a new operating system with 64 bits or even 128 bits, INT_MAX will still refer to the largest int available on your new system. The file "limits.h" contains a large number of such limits, all of which are available for your use simply by including the file in your program. It is a text file which can be opened in any editor and studied, a highly recommended exercise for you at this time. LOTS OF VARIABLE TYPES Example program ------> LOTTYPES.C Load the file LOTTYPES.C and display it on your screen. This file contains most of the standard simple data types available in the programming language C. Consult your compiler documentaion for a complete list of all types avialable with your compiler. There are other types, but they are the compound types (ie - arrays and structures) that we will cover in due time in this tutorial. C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (4 of 12) [4/15/1999 2:47:34 AM] Observe the file. First we define a simple int, followed by a long int . Next we have a short int which has a range that may be identical to that for the int variable. The unsigned is next and is defined as the same size as the int but with no sign. It should be pointed out that when the long, short, or unsigned is desired, the int is optional and is left out by most experienced programmers. Your compiler may differ significantly from the ranges given in the above table, so you should check the documentation for your compiler for the exact ranges for each type. The double is a floating point number but covers a greater range than the float and has more significant digits for more precise calculations. It also requires more memory to store a value than the simple float. The long double will cover a much larger range and store more significant digits, but it will also take longer to do calculations because of the increased size of data being used. Another diversion is in order at this point. Your compiler probably has no provision for floating point math, only double floating point math. It will promote a float to a double before doing calculations and therefore only one math library will be needed. Of course, this is transparent to you, so you don't need to worry about it. Because of this, you may think that it would be best to simply define every floating point variable as double, since they are promoted before use in any calculations, but that may not be a good idea. A float variable may require only 4 bytes of storage and a double may require 8 bytes of storage, so if you have a large volume of floating point data to store, the double will obviously require much more memory. If you don't need the additional range or significant digits, you should use the float type rather than the double. The compiler makes all floating point literals, such as the value 3.14159 in line 19, double constants by default. Some compilers will then issue a warning about line 19 because we are assigning a double to a float. You can safely ignore the warning at this time. After defining the data types in the program under consideration, a numerical value is assigned to each of the defined variables in order to demonstrate the means of outputting each to the monitor. SOME LATE ADDITIONS As any programming language evolves, additional constructs are added to fill some previously overlooked need. Two new keywords have been added to C with the release of the ANSI-C standard. They are not illustrated in example programs, but they will be discussed here. The two new keywords are const and volatile and are used to tell the compiler that variables of these types will need special consideration. A constant is declared with the const keyword and declares a value that cannot be changed by the program. If you inadvertently try to modify an entity defined as a const, the compiler will generate an error. This is an indication to you that something is wrong. Declaring an entity as const allows the optimizer to do a better job which could make your program run a little faster. Since constants can never have a value assigned to them in the executable part of the program, they must always be initialized. If volatile is used, it declares a value that may be changed by the program but it may also be changed by some outside influence such as a clock update pulse incrementing the stored value. This prevents the optimizer from getting too ambitious and optimizing away something that it thinks will never be changed. Examples of use in declaring constants of these two types are given as; const int index1 = 2; const index2 = 6; const float big_value = 126.4; C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (5 of 12) [4/15/1999 2:47:34 AM] volatile const int index3 = 12; volatile int index4; THE CONVERSION CHARACTERS Following is a list of some of the conversion characters and the way they are used in the printf() statement. A complete list of all of the conversion characters should be included with the documentation for your compiler. You do not need to understand all of these at this time, but you should know that there is a lot of flexibility available when you are ready to use it. d decimal notation i decimal notation (new ANSI standard extension) o octal notation x hexadecimal notation u unsigned notation c character notation s string notation f floating point notation Each of these is used following a percent sign to indicate the type of output conversion desired. The following fields may be added between those two characters. - left justification in its field (n) a number specifying minimum field width . to separate n from m (m) significant fractional digits for a float l to indicate a long These are all used in the examples which are included in the program named LOTTYPES.C, with the exception of the string notation which will be covered later in this tutorial. Lines 33 through 35 illustrate how to set the field width to a desired width, and lines 39 and 40 illustrate how to set the field width under program control. The field width for the float type output in lines 43 through 47 should be self explanatory. Compile and run this program to see what effect the various fields have on the output. You now have the ability to display any of the data fields in the previous programs and it would be to your advantage to go back and see if you can display some of the fields anyway you desire. COMBINING THE VARIOUS TYPES Example program ------> COMBINE.C Examine the file named COMBINE.C for examples of combining variables of the various types in a program. Many times it is necessary to multiply an int type variable times a float type variable and C allows this by providing a strict set of rules it will follow in order to do such combinations. Five variables of three different types are declared in lines 4 through 6, and three of them are initialized so we have some data to work with. Line 8 gives an example of adding an int variable to a float variable and assigning the result to a char type variable. The cast is used to control the type of addition and is indicated by defining the desired type within parentheses in front of the variable as shown. This forces each of the two variables to the char type prior to doing the addition. In some cases, when the cast is C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (6 of 12) [4/15/1999 2:47:34 AM] used, the actual bit patterns must be modified internally in order to do the type coercion. Lines 9 through 11 perform the same addition by using different kinds of type casting to achieve the final result. Note that the addition is not the same in all three cases because the addition is done using different types, so could conceivably result in different answers. Lines 13 through 15 illustrate the use of the cast to multiply two float variables. In two of the cases the intermediate results are cast to the int type, with the result being cast back to the float type. The observant student will notice that these three lines will not necessarily produce the same result. Be sure to compile and execute this program. When you do, you may get a lot of type conversion warnings which can be ignored at this point. In this program, we are illustrating things that can be done with no regard to whether it is good to do so in a production program. Note that all of the warnings can be eliminated by including the proper cast when we use different types. LOGICAL COMPARES Example program ------> COMPARES.C Load and view the file named COMPARES.C for many examples of compare statements in C. We begin by defining and initializing nine variables to use in the following compare statements. The first group of compare statements represents the simplest kinds of compares because they simply compare two variables. Either variable could be replaced with a constant and still be a valid compare, but using two variables for the compare is the general case. The first compare checks to see if the value of x is equal to the value of y and it uses the double equal sign for the comparison. Since x is equal to y, the variable z will be assigned the value of -13. A single equal sign could be used here but it would have a different meaning as we will see shortly. The second comparison checks to see if the current value of x is greater than the current value of z. The third compare introduces the not operator, the exclamation, which can be used to invert the result of any logical compare. The fourth checks for the value of b less than or equal to the value of c, and the last checks for the value of r not equal to the value of s. As we learned in the last chapter, if the result of the compare is true, the statement following the if clause will be executed and the results are given in the comments. Note that "less than" and "greater than or equal to" are also available, but are not illustrated here. It would be well to mention the different format used for the if statement in this example program. A carriage return is not required as a statement separator and by putting the conditional clause on the same line as the if, it adds to the readability of the overall program in this case. MORE COMPARES The compares in the second group are a bit more involved. Starting with the first compare, we find a rather strange looking set of conditions in the parentheses. To understand this we must understand just what a true or false is in the C language. A false is defined as a value of zero, and true is defined as any non-zero value. Any integer or character type of variable can be used for the result of a true/false test, or the result can be an implied integer or character. Look at the first compare of the second group of compare statements. The conditional expression "r != C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (7 of 12) [4/15/1999 2:47:34 AM] s" will evaluate as a true since the value of r was set to 0.0 in line 13, so the result of the compare will be a non-zero value. With all ANSI-C compilers, it will be set to a 1. Good programming practice would be to not use the resulting 1 in any calculations, but only for logical control. Even though the two variables that are compared are float variables, the logical result will be of type int. There is no explicit variable to which it will be assigned so the result of the compare is an implied int. Finally, the resulting number, is assigned to the integer variable x. If double equal signs were used, the phantom value, namely 1, would be compared to the value of x, but since the single equal sign is used, the value 1 is simply assigned to the variable named x, as though the statement were not in parentheses. Finally, since the result of the assignment in the parentheses was non-zero, the entire expression is evaluated as true, and z is assigned the value of 1000. Thus we accomplished two things in this statement, we assigned x a new value, and we assigned z the value of 1000. We covered a lot in this statement so you may wish to review it before going on. The important things to remember are the values that define true and false, and the fact that several things can be assigned in a conditional statement. The value assigned to the variable x was probably a 1, but remember that the only requirement is that it is nonzero. The ANSI-C standard says that the result of a comparison operation, ( >, >=, <, or <=) must be 1 or 0, but does not state the result of an equality operation. If you assume 0 or 1 will be returned, and only use it for control, you will not get into trouble. The example in line 20 should help clear up some of the above in your mind. In this example, x is assigned the value of y, and since the result is 11, the condition is non-zero, which is true, and the variable z is assigned 222. The third example of the second group in line 21, compares the value of x to zero. If the result is true, meaning that if x is not zero, then z is assigned the value of 333, which it will be. The last example in this group illustrates the same concept, since the result will be true if x is non-zero. The compare to zero in line 21 is not actually needed and the result of the compare is true. The third and fourth examples of this group are therefore logically identical. Of course we assign a different value to z in each case. ADDITIONAL COMPARE CONCEPTS The third group of compares will introduce some additional concepts, namely the logical "and" and the logical "or" operators. We assign the value of 77 to the three integer variables simply to get started again with some defined values. The first compare of the third group contains the new control &&, which is the logical "and" which results in a true if both sides of the "and" are true. The entire statement reads, if x equals y and if x equals 77 then the result is true. Since this is true, the variable z is set equal to 33. Note that only integral types can be "anded", so float and double types cannot be used here. The next compare in this group introduces the || operator which is the logical "or" operator which results in a true if either side of the "or" is true. The statement reads, if x is greater than y or if z is greater than 12 then the result is true. Since z is greater than 12, it doesn't matter if x is greater than y, because only one of the two conditions must be true for the result to be true. The result is true, therefore z will be assigned the value of 22. Once again, float and double cannot be "ored". LOGICAL EVALUATION (SHORT CIRCUIT) When a compound expression is evaluated, the evaluation proceeds from left to right and as soon as the result of the outcome is assured, evaluation stops. Therefore, in the case of an "and" evaluation, when one of the terms evaluates to false, evaluation is discontinued because additional true terms cannot make C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (8 of 12) [4/15/1999 2:47:34 AM] the result ever become true. In the case of an "or" evaluation, if any of the terms is found to be true, evaluation stops because it will be impossible for additional terms to cause the result to be false. In the case of additionally nested terms, the above rules will be applied to each of the nested levels. This is called short-circuit evaluation since the remaining terms are not evaluated. Going on to the next example in group three in line 29, we find three simple variables used in the conditional part of the compare. Since all three are non-zero, all three are true, and therefore the "and" of the three variables is true, leading to the result being true, and z is assigned the value of 11. Note that since the variables, r, s, and t are float type variables, they could not be used this way. Continuing on to line 30 we find three assignment statements in the compare part of the if statement. If you understood the above discussion, you should have no difficulty understanding that the three variables are assigned their respective new values, and the result of all three are non-zero, leading to a resulting value of true. THIS IS A TRICK, BE CAREFUL The last example of the third group contains a bit of a trick, but since we have covered it above, it is nothing new to you. Notice that the first part of the compare evaluates to false since x is not currently 2. The remaining parts of the compare are not evaluated, because it is a logical "and" so it will definitely be resolved as a false because the first term is false. If the program was dependent on the value of y being set to 3 in the next part of the compare, it will fail because evaluation will cease following the false found in the first term. Likewise, the variable named z will not be set to 4, and the variable r will not be changed. This is because C uses short circuit evaluation as discussed earlier. POTENTIAL PROBLEM AREAS The last group of compares illustrate three possibilities for getting into a bit of trouble. All three have the common result that the variable z will not be handled properly, but for different reasons. In line 37, the compare evaluates as true, but the semicolon following the second parentheses terminates the if clause, and the assignment statement involving z is always executed as the next statement. The if therefore has no effect because of the misplaced semicolon. This is actually a null statement and is legal in C, but the programmer probably did not intend to include the extra semicolon. The statement in line 38 is much more straightforward because the variable x will always be equal to itself, therefore the inequality will never be true, and the entire statement will never do a thing, but is wasted effort. The statement in line 39 will always assign 0 to x and the compare will therefore always be false, never executing the conditional part of the if statement. The conditional statement is extremely important and must be thoroughly understood to write efficient C programs. If any part of this discussion is unclear in your mind, restudy it until you are confident that you understand it thoroughly before proceeding onward. Compile and run this program. You may gets lots of conversion warnings which you can either ignore or fix up the code with casts to eliminate. Add some printout to see the results of some of the operations. THE CRYPTIC PART OF C Example program ------> CRYPTIC.C There are three constructs used in C that make no sense at all when first encountered because they are not C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (9 of 12) [4/15/1999 2:47:34 AM] intuitive, but they may increase the efficiency of the compiled code and are used extensively by experienced C programmers. You should therefore be exposed to them and learn to use them because they will appear in most, if not all, of the programs you see in the publications. Load and examine the file named CRYPTIC.C for examples of the three new constructs. In this program, some variables are defined and initialized in the same statements for use later. The statement in line 8 simply adds 1 to the value of x, and should come as no surprise to you. The next two statements also add one to the value of x, but it is not intuitive that this is what happens. It is simply by definition that this is true. Therefore, by definition of the C language, a double plus sign either before or after a variable increments that variable by 1. Additionally, if the plus signs are before the variable, the variable is incremented before it is used, and if the plus signs are after the variable, the variable is used, then incremented. In line 11, the value of y is assigned to the variable z, then y is incremented because the plus signs are after the variable y. In the last statement of the incrementing group of example statements, line 12, the value of y is incremented then its value is assigned to the variable z. To use the proper terminology, line 9 uses the postincrement operator and line 10 uses the preincrement operator. The next group of statements illustrate decrementing a variable by one. The definition works exactly the same way for decrementing as it does for incrementing. If the minus signs are before the variable, the variable is decremented, then used, and if the minus signs are after the variable, the variable is used, then decremented. The proper terminology is the postdecrement operator and the predecrement operator. You will use this construct a lot in your C programs. THE CRYPTIC ARITHMETIC OPERATOR Another useful but cryptic operator is the arithmetic operator. This operator is used to modify any variable by some constant value. The statement in line 23 adds 12 to the value of the variable a. The statement in line 24 does the same, but once again, it is not intuitive that they are the same. Any of the four basic functions of arithmetic, +, -, *, or /, can be handled in this way, by putting the operation desired in front of the equal sign and eliminating the second reference to the variable name. It should be noted that the expression on the right side of the arithmetic operator can be any valid expression, the examples are kept simple for your introduction to this new operator. Just like the incrementing and decrementing operators, the arithmetic operator is used extensively by experienced C programmers and it would pay you well to understand it thoroughly. THE CONDITIONAL EXPRESSION The conditional expression is just as cryptic as the last two, but once again it is very useful so it would pay you to understand it. It consists of three expressions separated by a question mark and a colon. The expression prior to the question mark is evaluated to determine if it is true or false. If it is true, the expression between the question mark and the colon is evaluated, and if the compare expression is not true, the expression following the colon is evaluated. The result of one of the evaluations is used for the assignment as illustrated in line 30. The final result is identical to that of an if statement with an else clause. This is illustrated by the example in lines 32 through 35 of this group of statements. The conditional expression has the advantage of more compact code that may compile to fewer machine instructions in the final program. Lines 37 and 38 of this example program are given to illustrate a very compact way to assign the greater C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (10 of 12) [4/15/1999 2:47:34 AM] of the two variables a or b to the variable c, and to assign the lessor of the same two variables to the variable c. Notice how efficient the code is in these two examples. TO BE CRYPTIC OR NOT TO BE CRYPTIC Several students of C have stated that they didn't like these three cryptic constructs and that they would simply never use them. This would be fine if they never have to read anybody else's program, or use any other programs within their own. You will find many functions that you wish to use within a program but need a small modification to use it, requiring you to understand another person's code. It would therefore be to your advantage to learn these new constructs, and use them. They will be used in the remainder of this tutorial, so you will be exposed to them. This has been a long chapter but it contained important material to get you started in using C. In the next chapter, we will go on to the building blocks of C, the functions. At that point, you will have enough of the basic materials to allow you to begin writing meaningful programs. STYLE ISSUES We have no specific issues of style in this chapter other than some of the coding styles illustrated in the example programs. Most of these programs are very nontypical of real C programs because there is never a need to list all of the possible compares in a real program, for example. You can use the example programs as a guide to good style even though they are not real programs. WHAT IS AN l-value AND AN r-value? You will sometimes see a reference to an l-value or a r-value in writings about C or in the documentation for your C compiler. Every variable has an r-value which is defined as the actual value stored in the variable, and it also has an l-value which is defined as the name of the variable. Therefore, the variable depicted graphically in figure 4-1 has an l-value of index, and an r-value of 137 since 137 is the value stored in the variable at this time. The definition for this variable would be given as follows; int index = 137; PROGRAMMING EXERCISES 1. Write a program that will count from 1 to 12 and print the count, and its square, for each count. Write a program that counts from 1 to 12 and prints the count and its inversion to 5 decimal places for each count. This will require a floating point number. 2. Write a program that will count from 1 to 100 and print only those values between 32 and 39, one to a line. Use the incrementing operator for this program. 3. Return to Table of Contents Advance to Chapter 5 Copyright © 1988-1997 Coronado Enterprises - Last update, March 15, 1997 C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (11 of 12) [4/15/1999 2:47:34 AM] Gordon Dodrill - dodrill@swcp.com - Please email any comments or suggestions. C Tutorial - Chapter 4 file:///E|/education/C LANGUAGE TUTORIAL/chap04.htm (12 of 12) [4/15/1999 2:47:34 AM] C Tutorial - Chapter 5 FUNCTIONS, VARIABLES, AND PROTOTYPES OUR FIRST USER DEFINED FUNCTION Example program ------> SUMSQRES.C Load and examine the file SUMSQRES.C for an example of a C program with functions. Actually this is not the first function we have encountered because the main program we have been using all along is technically a function, as is the printf() function. The printf() function is a library function that was supplied with your compiler. We will finally define what line 3 is for in this chapter but not until we get to about the fourth example program, so continue to wait patiently and ignore that line for the time being. Notice the executable part of this program which begins in line 10 with a line of code that simply says "header();", which is the way to call any function. The parentheses are required because the C compiler uses them to determine that it is a function call and not simply a misplaced variable. When the program comes to this line of code, the function named header() is called, its statements are executed, and control returns to the statement following this call. Continuing on, we come to a for loop which will be executed 7 times and which calls another function named square() each time through the loop. Finally, a function named ending() will be called and executed. For the moment ignore the variable name index in the parentheses of the call to square(). We have seen that this program calls a header, 7 square calls, and an ending. Now we need to define the functions. DEFINING THE FUNCTIONS Following the main program you will see a function beginning in line 19 that follows all of the rules set forth so far for a main program except that it is named header(). This is the function which is called from line 10 of the main program. Each of these statements are executed, and when they are all complete, control returns to the main program, or more properly, the main() function. The first statement sets the variable named sum equal to zero because we plan to use it to accumulate a sum of squares. Since the variable named sum is defined prior to the main program, it is available for use in any of the functions which are defined after the variable is defined. It is called a global variable, and its scope is the entire program including all functions. It is also sometimes referred to as a file variable because it is available throughout the file. More will be said about the scope of variables near the end of this chapter. The statement in line 22 outputs a header message to the monitor. Program control then returns to the main() function since there are no additional statements to execute in this function. Essentially, we drop out of the bottom of the function and return to the caller where we begin executing statements immediately following where the call was made from. It should be clear to you that the two executable lines from this function could be moved to the main program, replacing the header call, and the program would do exactly the same thing that it does as it is now written. This does not minimize the value of functions, it merely illustrates the operation of this simple function in a simple way. You will find functions to be very valuable in C programming. C Tutorial - Chapter 5 file:///E|/education/C LANGUAGE TUTORIAL/chap05.htm (1 of 10) [4/15/1999 2:47:53 AM] PASSING A VALUE TO A FUNCTION (CLASSIC METHOD) Going back to the main program, and the for loop specifically, we find the new construct from the end of the last lesson used in the last part of the for loop, namely the index++ used in line 11. You should get familiar with this construct, as you will see it in a lot of C programs. In the call to the function named square(), we have an added feature, the variable name index within the parentheses. This is an indication to the compiler that when you jump to the function, you wish to take along the value of index to use during the execution of that function. Looking ahead at the function named square() in line 26, we find that another variable name is enclosed in its parentheses, the variable number. This is the name we prefer to call the variable passed to the function when we are executing code within the function. We can call it anything we wish as long as it follows the rules of naming an identifier and is not a keyword. Since the function must know what type the variable is, it is defined following the function name but before the opening brace of the function itself. Therefore, line 23 containing the expression "int number;" tells the function that the value passed to it will be an int type variable. With all of that out of the way, we now have the value of index from the main program passed to the function square(), but renamed number, and available for use within the function. This is the classic style of defining function variables and has been in use since C was originally defined. A newer and much better method is gaining in popularity due to its many benefits and will be discussed later in this chapter. Following the opening brace of the function, we define another variable named numsq for use only within the function itself, (more about that later) and proceed with the required calculations. We set the variable named numsq equal to the square of the value of number, then add numsq to the current total stored in the variable named sum. You should remember that the expression "sum += numsq;" has the same meaning as "sum = sum + numsq;" from the last lesson. We print the number and its square in line 33, and return to the main program. MORE ABOUT PASSING A VALUE TO A FUNCTION When we passed the value of the variable named index to the function, a little more happened than meets the eye. We didn't pass the variable named index to the function, we actually passed a copy of the value. In this way, the original value is protected from accidental corruption by the called function. We could have modified the variable named number in any way we wished in the function named square(), and when we returned to the main program, the variable named index would not have been modified. We thus protect the value of a variable in the calling function from being accidentally corrupted, but we cannot return a value to the calling function from a called function using this technique. We will find a well defined method of returning values to the main() function or to any calling function when we get to arrays and another method when we get to pointers. Until then, the only way you will be able to communicate back to the calling function will be with global variables. We have already hinted at global variables above, and will discuss them in detail later in this chapter. Continuing in the main() function, we come to the last function call, the call to the function named ending() in line 13. This line calls the last function which has no local variables defined. It prints out a message with the value of the variable sum contained in it to end the program. The program ends by returning to the main() functoin and finding nothing else to do, so the program terminates. Compile and run this program and observe the output. C Tutorial - Chapter 5 file:///E|/education/C LANGUAGE TUTORIAL/chap05.htm (2 of 10) [4/15/1999 2:47:53 AM] NOW TO CONFESS A LITTLE LIE I told you a short time ago that the only way to get a value back to the calling function was through use of a global variable, but there is another way which we will discuss after you load and display the program named SQUARES.C. In this example program we will see that it is simple to return a single value from a called function to the calling function. But once again, it is true that to return more than one value, we will need to study either arrays or pointers. Example program ------> SQUARES.C In the main() function, we define two integers and begin a for loop in line 8 which will be executed 8 times. The first statement within the for loop is "y = squ(x);", which is a new and rather strange looking construct. From past experience, we should have no trouble understanding that the squ(x) portion of the statement is a call to the function named squ() taking along the value of x as a parameter. Looking ahead to line 20 of the function itself, we find that the function prefers to call the input variable input, and it proceeds to square the value of input and call the result square. Finally, a new kind of a statement appears in line 26, the return statement. The value within the parentheses is assigned to the function itself and is returned as a usable value in the main program. Thus, the function call "squ(x)" is assigned the value of the square and returned to the main program such that the variable named y is then set equal to that value. If the variable named x were therefore assigned the value 4 prior to this call, y would then be set to 16 as a result of the code in line 10. The parentheses around the return value in line 26 are not required, but are included by many experienced C programmers. Another way to think of this is to consider the grouping of characters squ(x) as another variable with a value that is the square of x, and this new variable can be used any place it is legal to use a variable of its type. The values of the variables x and y are then printed out. To illustrate that the grouping of squ(x) can be thought of as just another variable, another for loop is introduced in line 14 in which the function call is placed within the printf() statement rather than assigning it to a new variable. One last point must be made, the type of variable returned must be defined in order to make sense of the data, but the compiler will default the type to int if none is specified. If any other type is desired, it must be explicitly defined. How to do this will be demonstrated in the next example program. We are simply using the default return type in this program. Be sure to compile and run this program which also uses the classic method of defining function variables. Once again, any warnings can be ignored. FLOATING POINT FUNCTIONS Example program ------> FLOATSQ.C Load the program FLOATSQ.C for an example of a function in the classic style with a float type of return. It begins by defining a global floating point variable named z which we will use later. Then in the main part of the program, an integer is defined, followed by two floating point variables, and then by two strange looking definitions. The expressions sqr() and glsqr() look like function calls. This is the proper way to define that a function will return a value that is not of type int, but of some other type, in this case C Tutorial - Chapter 5 file:///E|/education/C LANGUAGE TUTORIAL/chap05.htm (3 of 10) [4/15/1999 2:47:53 AM] float. This tells the compiler that when a value is returned from either of these two functions, it will be of type float. This is, once again, the classic method of defining functions and is all but obsolete now. Note that neither function is actually called by the code in line 9, these only declare the return type for these two functions. Now refer to the function named sqr() starting in line 29 and you will see that the function name is preceded by the keyword float. This is an indication to the compiler that this function will return a value of type float to any program that calls it. The type of the function return is now compatible with the call to it. The line following the function name contains float inval;, which indicates to the compiler that the variable passed to this function from the calling program will be of type float. Since we told the caller we would be returning a float type, we actually return the value in line 35 so everything matches up. The function named glsqr() beginning in line 39, will also return a float type variable, but it uses a global variable for input. It does the squaring right within the return statement and therefore has no need to define a separate variable to store the product. The function sqr() could have done the squaring right in the return also, but was done separately as an illustration of what can be done. The overall structure of this program should pose no problem and will not be discussed in any further detail. As is customary with all example programs, compile and run this program and ignore any warnings you may get. THE CLASSIC STYLE The three programs we have studied in this chapter so far use the classic style of function definition. Although this was the first style defined for C, it is rapidly being replaced with a more modern method of function definition because the modern method does so much for you in detecting and flagging errors. As you read articles on C, you will see programs written in the classic style, so you need to be capable of reading them. This is the reason the classic style was included in this chapter. It would be highly recommended, however, that you learn and use the modern method which will be covered shortly in this tutorial. In fact, you are advised to never use the classic style for any of your programming efforts. The book by Kernigan and Ritchie, "The C Programming Language - Second Edition" is the definitive text of the classic style of C programming. The remainder of this tutorial will use the modern method as recommended and defined by the ANSI-C standard. If you have an older compiler, it may not work on some of these files and it will be up to you to modify the programs as needed to conform to the classic style. Actually, the ANSI-C standard is used so universally, if you have a non-ANSI compiler you should use it only as a doorstop and purchase a good ANSI compatible compiler for the rest of your studies. THE RETURN TYPE OF main() In the original K&R definition of C, all functions returned an int type variable by default, unless the author specified something different. Since explicitly returning a value when leaving a function was optional, most C was written in the following manner; main() { ... C Tutorial - Chapter 5 file:///E|/education/C LANGUAGE TUTORIAL/chap05.htm (4 of 10) [4/15/1999 2:47:53 AM] } When prototyping was added to the language (which we will study shortly), many programmers apparently thought the main() function didn't return anything, so used the void type for a return and it became a common practice to write the main() function as follows; void main() { ... } When the ANSI-C standard was finalized the only return type approved by the standard is an int type variable. A good compiler will check that the program actually returns a value by requiring that an integer is returned from each exit point. This led to the following form for main(); int main() { ... return 0; } Apparently because of the inertia behind the use of a void return, many compiler writers added the void return as an extension to permit the use of legacy code without modifications. Some compilers therefore support the void return but the int return is the only method approved by the ANSI-C standard. In order to make your code as portable as possible, you should always use the last form above. You can finally see why we have been adding the line that returns a value of zero to the operating system. This indicates to the operating system that the program executed normally. SCOPE OF VARIABLES Example program ------> SCOPE.C Load the next program, SCOPE.C, and display it for a discussion of the scope of variables in a program. You can ignore the 4 statements in lines 2 through 5 of this program for a few moments. We will discuss them later. We will spend a good deal of time in this program and cover a lot of new topics. Many of the topics covered here will not seem to be particularly useful, but stay with it because they are very important. WHAT IS A GLOBAL VARIABLE? The variable defined in line 7 is a global variable named count which is available to any function in the program since it is defined before any of the functions. It is always available because it exists during all the time that the program is being executed. (That will make sense shortly.) Farther down in the program, another global variable named counter is defined in line 29 which is also global but is not available to the main() function since it is defined following the main() function. A global variable is any variable that is defined outside of any function. Note that both of these variables are sometimes referred to as external variables because they are external to any functions, and they are sometimes also called file variables. C Tutorial - Chapter 5 file:///E|/education/C LANGUAGE TUTORIAL/chap05.htm (5 of 10) [4/15/1999 2:47:53 AM] Global variables are automatically initialized to zero when they are defined. Therefore, the variables named count and counter will both be initialized to a value of 0. Return to the main() function and you will see the variable named index defined as an int in line 11. Ignore the word register for the moment. This variable is only available within the main() function because that is where it is defined. In addition, it is an automatic variable, which means that it only comes into existence when the function in which it is contained is invoked, and ceases to exist when the function is finished. This really means nothing here because the main() function is always in operation, even when it gives control to another function. Another integer is defined within the for loop braces named stuff. Any pairing of braces can contain variable definitions which will be valid and available only while the program is executing statements within those braces. The variables will be automatic variables and will cease to exist when execution leaves the braces. The variable named stuff will therefore be created and destroyed 8 times, once for each pass through the loop. MORE ON AUTOMATIC VARIABLES Observe the function named head1() in line 30 which looks a little funny because of void being used twice. The purpose of the use of the word void will be explained shortly. The function contains a variable named index, which has nothing to do with the variable named index in line 11 of the main() function, except that both are automatic variables. When the program is not actually executing statements in this function, this variable named index does not even exist. When head1() is called, the variable is generated, and when head1() completes its task, the variable in head1() named index is eliminated completely from existence. (The automatic variable is stored on the stack. This topic will be covered later.) Keep in mind however that this does not affect the variable of the same name in the main() function, since it is a completely separate entity. Automatic variables therefore, are automatically generated and disposed of when needed. The important thing to remember is that from one call of a function to the next call, the value of an automatic variable is not preserved and must therefore be reinitialized. WHAT ARE STATIC VARIABLES? An additional variable type must be mentioned at this point, the static variable. By putting the keyword static in front of a variable definition within a function, the variable or variables in that definition are static variables and will stay in existence from call to call of the particular function. A static variable is initialized once, at load time, and is never reinitialized during execution of the program. By putting the static keyword in front of an external variable, one outside of any function, it makes the variable private and not accessible to use in any other file. (This is a completely different use of the same keyword.) This implies that it is possible to refer to external variables in other separately compiled files, and that is true. Examples of this usage will be given in chapter 14 of this tutorial. They are not illustrated here. USING THE SAME NAME AGAIN Refer to the function named head2(). It contains another definition of the variable named count. Even though count has already been defined as a global variable in line 7, it is perfectly all right to reuse the name in this function. It is a completely new variable that has nothing to do with the global variable of the same name, and causes the global variable to be unavailable within this function. This allows you to C Tutorial - Chapter 5 file:///E|/education/C LANGUAGE TUTORIAL/chap05.htm (6 of 10) [4/15/1999 2:47:53 AM] write programs using existing functions without worrying about what names were used for global variables or in other functions because there can be no conflict. You only need to worry about the variables that interface with the functions. WHAT IS A REGISTER VARIABLE? Now to fulfill a promise made earlier about what a register variable is. A computer can keep data in a register or in memory. A register is much faster in operation than memory but there are very few registers available for the programmer to use. If there are certain variables that are used extensively in a program, you can designate that those variables are to be stored in a register in order to speed up the execution of the program. The method of doing this is illustrated in line 11. Your compiler probably allows you to use one or more register variables and will ignore additional requests if you request more than are available. The documentation for your compiler should list how many registers are available with your compiler. It will also inform you of what types of variables can be stored in a register. If your compiler does not allow the use of register variables, the register request will simply be ignored. WHAT IS PROTOTYPING? A prototype is a model of a real thing and when programming in ANSI-C, you have the ability to define a model of each function for the compiler. The compiler can then use the model to check each of your calls to the function and determine if you have used the correct number of arguments in the function call and if they are of the correct type. By using prototypes, you let the compiler do some additional error checking for you. The ANSI standard for C contains prototyping as part of its recommended standard. Every ANSI-C compiler will | |