You are on page 1of 79

What is C++

What is C++:

You can see that the C programming language was developed first, C++ was developed later. You might be asking yourself what, exactly, is C++ and how does it relate to C? The answer is that C++ is essentially C taken to the next level. The most obvious difference between the two is that C++ supports ob ect orientation. !owever, C++ sports many other improvements over C. "or example, C++ handles strings better than C, and has a more robust exception handling. #$xception handling refers to aprogram%s ability to handle unexpected errors. &hat if the user inputs a 'erothen tries to divide by that number? This is an exception, how your code handles it is exception handling. C code will compile fine in most C++ compilers, but the reverse is not true. C++ code will not necessarily compile in a C compiler. You may be wondering what is meant by the word code. Code is essentially the series of programming commands that a programmer writes. (ll the commands that make up a program are the source code for that program. C++ supports all C commands and also has many additions. You may fre)uently see old style C code mixed in with C++ code, especially in programs written by programmers who originally started in C.

C++ Fundamentals
C++ Fundamentals:

C++ is a programming language. As such,it shares anumber of similarities with other programming languages. First we may need to clarify what a programming language is. A computer thinks in 1s and 0s. arious switches are either on !1s", or off !0s". #ost

humans, howe$er, ha$e trouble thinking in 1s and 0s. A programming language is a language that pro$ides a bridge between the computer and human beings. A %low&le$el' language is one that is closer to a computers thinking than to a human language. A prime e(ample would be Assembly language. A %high&le$el' language is one that is closer to human language. C)*)+ and *A,-C are prime e(amples of high&le$el language. #any people consider C and C++ to be high&le$el languages, but actually C and C++ are both somewhatof a bridge between the low&le$el languages and high&le$el languages. .ou might think of them as mid&le$el languages. /he le$el of a

language, in this conte(t, essentially refers to how far it is remo$ed from actual machine language.

0ach programming language has $arious strengths and weaknesses. ,ome, like *A,-C, are easy to usebut are neither fle(ible nor powerful. )thers, such as Assembly, are powerful, but difficult to use. C and C++ are somewhere in the middle. C++ is 1uite powerful, but relati$ely easy to use !easier than Assembly but more difficult than *A,-C". ,ome languages are also written with specific purposes in mind. Fortran was written specifically for mathematical programming,*A,-C was designed simply for teaching programming, and C)*)+was designed for business applications. C++ was designed as a general purpose language. -t is used in business applications,telecommunications programming, artificial intelligence prog&ramming,games programming, and much more. /his is one reason why it is the language that many teachers choose to teach students.)nce youha$e learned C++, you can use it in a wide $ariety of situations.

2rograms are written to handle data./his is why the industry as a whole is often referred to as data processing,information technology, computer information systems, and soon. /hat data might be information about employees, parts toa mathematicalcomputation, scientific data, or e$en the elements of a game.3o matter what programming language or techni1ues you use,the ultimate goal of programming is to store, manipulate, and retrie$e data. 4ata must be temporarily stored in the program, in order to be manipulated. /his is accomplished $ia $ariables.

A $ariable is simply a place in memory set aside to hold data of a particular type. -t is a specific section of the computers memory that has been reser$ed to hold some data. -t is called a $ariable because its $alue or content can $ary. 5hen you createa $ariable,you are actually setting aside a small piece of memory for storage purposes. /he name you gi$e the $ariable is actually a label for that address in memory. For e(ample, you might declare a $ariable in the following manner.

int 67 /hen, you ha$e 6ust allocated four bytes of memory7 you are using the $ariable 6 to refer to those four bytes of memory..ou are also stating that the only type of data that 6 will hold, is whole numbers. !/he int is a data type that refers to integers, or whole numbers." 3ow, whene$er you reference 6 in your code, you are actually referencing the contents being stored at a specific address in memory.

5ith that said, you might now be asking what is meantby %data of a particular type'8 4ata comes in different types. ,ome data consists of letters and some consists of numbers. Any programming language will recogni9e only certain types or categories of data. /he basic data types that C++ recogni9es, and what they hold, are shown in /able 1.1. -n addition, thereare a few other data types that will be introduced later in the book.

Datatypes int long float double char bool

Values Stored This value is for whole numbers, or integers. The si'e depends on the operating systems. *n +,-bit operating systems, the int is usually +, bits #. bytes/ in length. This data type holds larger whole numbers "loats are used to hold decimal numbers such as ,.0,123 ( double is simply a really big float. ( char can store a single alpha-numeric type. *n other words, it can store a number or a letter. 4ool is short for 4oolean, a reference to 4oolean logic. Therefore, this data type can only store true or false. This is basically a small integer. 5sually , bytes in length. 4ut the actually si'e will depend on the operating system. 6n +,-bit operating systems such as like &indows 23, ,000, 7T, and 89, a short will be , bytes long.

short

5hen you are deciding what type of $ariable to create, you need to think about what kind of data you might wish to store in that $ariable. -f you want to store a persons age,then an int is a good choice. /he int data type will hold whole numbers, and will, in fact, hold numbers much larger than you might need for a persons age. /he long data type will also hold whole numbers, but it is designed for e$en larger whole numbers. -f you wished to store bank balances, grade point a$erages, or perhaps temperatures, you would need to consider using a float. /he float data type holds decimal $alues. :owe$er if you were storing astronomical data, you would still want to hold decimals, but because they might be 1uite large, you would ha$e to consider storing them in doubles.2icking what data type to use is actually simple. ;ust gi$e some thought to the type of data you intend to store in a $ariable.

-n addition to considering what type of $ariable you will use,you

must also pay attention to how you name the $ariable. )nly certain names are allowed in C++. ariable names must begin witha letter

or underscore and may contain any combination of upper<lower case characters, digits, and underscores. ariablenames can neither begin

with a number nor contain certain symbols such as =, >, ?, and so on. :ere are some e(amples of $alid and in$alid $ariable names !/able 1.@". Top

Valid Variable Names Invalid Variable Names (ccountnumber ;<ast7ame <ength;of;side Temperature :account <astname =length >temp

-n addition, many of the symbols that C++ does not allow you to use in naming your $ariables actually represent something important in the C++ programming language. /his is one reason whysuch symbols are not allowed in $ariable names. Also, please under&stand that simply because a name is $alid in C++ does not make ita good name. -t is important that your $ariable names bear some resemblance to the $alue they hold./he compiler will certainly let you compile your code without this, but it will make your code much more difficult for other programmers to understand. -f your $ariable holds an account number, please dont name the $ariable ( or i. -nstead, gi$e it a name such as accountAnumber or acctnum.

,ome programmers go further and add a notation at the beginning of the $ariable name to indicate what type of $ariable it is. For e(ample, an account number that is an int might be callediAaccountnum or intAccount3um. /he following table shows common prefi(es used for $arious data types. 3ot e$eryone follows thesenaming con$entions. 3e$ertheless, they are common enough that you should be aware of them. /hey are summari9ed in /able 1.B.

Variable Type int float long char bool

Common Naming Conventions iaccountnumber, i;accountnum, intaccountnum fbalance, f;balance, flt;balance lnumber, l;number, lngnumber c;value, chr?alue lnumber, l;number, lngnumber

/here is a plethora of ways to name $ariables7no way is right or wrong. /he thing to keep in mind is thisC 4oes your personal naming con$ention make it easy for others toread your code8 4oes your $ariables name clearly identify whattype of $ariable it is and<or what data it will hold8 -f you cananswer yes, then your naming con$ention is fine.

3ow that you know how to name $ariables,lets gi$e you a few e(amples. int intAaccountAnum7 boolean bturnedon7 float fltsalary7

3otice that these e(amples all obey the aforementioned rules for naming $ariables. .ou might, howe$er, be curious about the semicolon at the end of each line. 0ach statement in C++ !as well as C, ,un ;a$a, and se$eral other programming languages"ends with a semicolon. /he semicolon basically tells the compilerthat you are done with that particular line of code, and that thethings you ha$e written prior to that semicolon represent one single, concise statement. A statement is simply a single line of code that performs some action. #any programmers also use theterm e(pression when referring to a statement. /he two terms,e(pression and statement, are interchangeable.

.ou can declare more than one $ariable on a single line.All the $ariables declared in that statement will be of the typeyou declared at the beginning of the statement.

int iAaccountAnum, iAage, intAyearsAwAcompany7

All three $ariables are of type int.

:intD /his works the same way in many other programming languages suchas ;a$a and C,but does 3)/ work this way in isual *asicE. F5atchoutD

C++ is case sensiti$e. Gppercase letters and lowercase letters are treated as two different letters. An A is not the sameas an a./hat means that int main!" and int #ain!" are not the samething. )ne of the most common mistakes beginners make is forgettingthe case&sensiti$e nature of C++. .ou can choose to initiali9e your $ariable to some default $alue when you create it. /he following e(amples illustrate this.

int num H 07

float number H 0.07

A default $alue is simply some starting $alue that the $ariable will hold,by default, if no other $alue is placed into it.For e(ample, if your program was storing data about people who recently recei$ed a high school diploma, you might wish to use a default $alue of 1I, because that is the most probable age of a recent high school graduate.,

Statements and Expressions


Statements and Expressions:

As you ha$e already seen, a statement is simply a single line of code that performs some action. Jemember that another word for a statement is an e(pression. -n C++, a single e(pression does some type of action. /hat action might be to declare a $ariable, add two numbers, compare two $alues, or 6ust about anything at all. -t is also important to remember that all statements<e(pressions end with a semicolon. Another of the most common mistakes that beginners make is lea$ing off semi colons. +ets look at a few simple statements.

int iAacctnum7 iAacctnum H KKKKKK7 iAacctnum H iAacctnum + K7

0ach statement performs a different actionLbut it does perform some actionLand it ends with a semicolon. /he first statement<e(pression simply declares a $ariable. /he second

statement<e(pression sets that $ariable e1ual to some $alue. Finally, the last statement<e(pression performs addition and puts the answer in the $ariable that was pre$iously declared.

)perators .ou saw, at the end of the last section, the use of the + sign. /his is an operator. An operator is simply some symbol that performs some action, usually a mathematical action, such as addition or subtraction. C++ supports a number of important operators that you will need to get familiar with. +ets begin e(amining C++ operators, starting with the basic math operators, shown in /able 1.M.

perator + F

!urpose To add two numbers To subtract two numbers To multiply two numbers This is a special operator that simply ments the value by D. You will see this used later in this book when loops are discussed. This is also a special operator that simply decrements the value by D.

Example int answer@ answer A B +C@ int answer@ answer A D0 E+@ int answer@ answer A . F B@

G divide two numbers int answer@ answer A 1 G B@ ++ int answer@ incre answer++@

-A

int answer@ answer--@

The single e)uals sign is an assignment operator. *t states Hmake what%s on the answer A DC@ left e)ual to what%s on the rightI The double e)uals is an e)uality operator. *t asks His what%s on the left e)ual to what%s on the right?I This is if#answerAAB/ fre)uently used in if statements #which you will see in a later chapterJ/ 7ot e)ual to (dd then assign Kubtract then assign This is the logical 6M operator. This is the logical (7N operator 4itwise shift to the right 4itwise shift to the left 4itwise (nd 4itwise 6r if #x JA+/ x +A D@ x -AD@ if# AA B LL AAD0/ if# O B :: PD0/ +OO, +PP, +:, +L,
Top

AA

JA +A -A LL :: OO PP : L

5atchoutD 5hen using the increment !++" or decrement !L" operator, it is necessary to be careful of where you put it. -f you put the operator before the $ariable, then that operation will take place before any other operations in the e(pression. ,ome e(amples follow. int answer, num7 num H K7 3ow using the e(pression, answer H num++7 the $alue of num will first be put in answer, /:03 incremented. -n other words, the $alue of answer will be set to K, and then the $alue of num will be incremented. -f you want num to be incremented *0F)J0 you assign the $alue to answer then you must put the increment operator first, as shown in the following e(ample. answer H ++num7 /he operators shown in /able 1.M are your basic math operators and logical operators. /here are se$eral other operators you will also see in C++. /hese will be introduced in later chapters because they are pertinent to topics that will be co$ered in those chapters. #ost of the operators in /able 1.M should be familiar to you. /he math operators represent simple math operations. All math operators occur with a specific order. /he order is pretty much the same as the order of operations defined in mathematics. First is ? !multiplication", ne(t < !di$ision", then + !addition", and, finally, N !subtraction". /he increment ++ and decrement N operators precedence is determined by what side of the $ariable they are on. .ou can alter the order of operations by using parentheses, 6ust as you do in mathematics. An e(ample follows. answer H ( ? B + M7 First, ( and B would be multiplied, and then M would be added to that product.-f, instead, you wanted to add B and M, then multiply by (, you could simply use parentheses to denote that. answer H ( ? !B +M"7 /he order of multiplication&di$ision&addition&subtraction is simply the order defined by mathematics for these operations. ,ome teachers e$en use the mnemonic #y 4ear Aunt ,ally to help students to recall the proper order of operations. /he important thing to remember is that an operator is simply a symbol that defines some action to be taken. /he + symbol defines the action of addition and the O symbol defines the action of di$ision. )ther operators, such as the increment ++ operator, may be new to you, but the fact remains that they are simply symbols that define some action.An operator is considered to be a unary operator if it takes only one argument. 2ut another way, if a symbol only acts on one number then it is a unary operator. /he increment and decrement operators fall into this category. /hey only work on a single $ariable. *inary operators, on the other hand, work on two numbers. Addition and subtraction both work on two numbers. A more technical definition would be that binary operators are operators that take two arguments.

*asic ,tructure of a C++ program

3ow that you ha$e seen $ariable declaration, C++ e(pressions, and the basic math operators, lets take a 1uick look at the basic structure of a C++ program. All C++ programs must ha$e a main function. /his is where the program begins. A function is one or more statements grouped together in a logical manner to accomplish some goal under a common name. /he following is a basic C++ program. int main!" P return 07 Q 3ow, this program will not do muchLin fact, it wont do anything useful at all. -t is, howe$er, a $alid C++ program. -t has a main function that returns an integer $alue. /he main function is where all C++ programs start. /his is the starting point for your entire program. All main functions are re1uired by the A3,- !American 3ational ,tandards -nstitute" standards to return an integer. /he integer is a 0 if the program e(ecutes fine, and a 1 if some problem is encountered. /his was originally done because some operating systems re1uire any program to return a $alue telling the operating system that e$erything is )R. .ou will see a lot of 5indows programmers use a main function that returnsa $oid like the following. $oid main!" /his will work in some cases, but it is not technically correct. /his book endea$ors to conform to the A3,- standards and use return 0. /he ne(t thing to notice about our sample program is the presence of brackets. /hese brackets are C++s way of establishing borders around any block of code.!-ncidentally, C, ;a$a, and ;a$a,criptE do the same thing. +earning it here will help you learn other languages as well.". 0$ery time you see an opening bracket, Pthere must be a S matchingQ closing bracket. .ou will see a lot more about this when we discuss loops, decision structures, and functions. For now, suffice it to say that brackets form borders around blocks of code. 5ith all that said, lets look at a program that has a few statements. int main!" P int 67 6 H K7 6++7 return 07

/his simple program creates a $ariable named 6, sets the $alue of that $ariable to K, then increments that $alue by one. /his is still not a particularly e(citing piece of code, but it does illustrate the basic structure of a C++ program. /hree statements are e(ecuted, a 0 is returned to indicate that e$erything is )R, and there are brackets surrounding the main function. -f you carefully e(amine this code, and follow this template in all your programming, then you will do wellD Header Files /here is only one more item that needs to be discussed regarding the basic structure of a C++ program. /hat item is header

files. :eader files are files that contain the definitions for functions and<or classes. *asically, if you ha$e a lot of functions or $ariables that you might want to use in se$eral programs, you can put them in a header file, then include that header file anywhere you need to use it. After creating a header file you can then include a reference to a header file in your program and use the functions and<or classes defined in that header file. /he real intricacies of header files are discussed in a later chapter, in which you will actually create some header files. :owe$er, you should reali9e that there are a lot of these files built into C++ that you can useD 5ell, %built in' is not e(actly accurate. /hey are actually installed with your compiler and you can include them in your programs./his is demonstrated in the following e(ample. =include int main!" P return 07 Q

.ou now ha$e access to all the classes and functions defined in the iostream header file. -n the following chapters, you will see se$eral different header files, each pro$iding a different set of functions for you to use. For now, all that is important is that you reali9e that you include a header file using the = sign and the word include. -f the header file is one that is part of C++, then you simply use the . #ake sure that this is the first thing you do in your fileD Jemember that you use .cpp to indicate a C++ source file and .c to indicate a C source file, while the .h indicates a header source file. A source file is simply a plain te(t file that has the source code for your C++ program. ,ource code is the basic lines of programming language that you write, and that the compiler will later use as a source to create an e(ecutable program.

"asi# Stru#ture o$ a C++ !rogram


Basic Structure of a C++ Program:

3ow that you ha$e seen $ariable declaration, C++ e(pressions, and the basic math operators, lets take a 1uick look at the basic structure of a C++ program. All C++ programs must ha$e a main function. /his is where the program begins.A function is one or

more statements grouped together in a logical manner to accomplish some goal under a common name. /he following is a basic C++ program.

int main!" P return 07 Q

3ow, this program will not do muchLin fact, it wont do anything useful at all. -t is, howe$er, a $alid C++ program. -t has a main function that returns an integer $alue. /he main function is where all C++ programs start. /his is the starting point for your entire program. All main functions are re1uired by the A3,- !American 3ational ,tandards -nstitute" standards to return an integer. /he integer is a 0 if the program e(ecutes fine, and a 1 if some problem is encountered. /his was originally done because some operating systems re1uire any program to return a $alue telling the operating system that e$erything is )R. .ou will see a lot of 5indows programmers use a main function that returns a $oid like the following.

$oid main!"

/his will work in some cases, but it is not technically correct. /his book endea$ors to conform to the A3,- standards and use return 0.

/he ne(t thing to notice about our sample program is the presence of brackets. /hese brackets are C++s way of establishing

borders around any block of code. !-ncidentally, C, ;a$a, and ;a$a,criptE do the same thing. +earning it here will help you learn other languages as well.". 0$ery time you see an opening bracket, Pthere must be a matchingQ closing bracket. .ou will see a lot more about this when we discuss loops, decision structures, and functions. For now, suffice it to say that brackets form borders around blocks of code.

5ith all that said, lets look at a program that has a few statements.

int main!" P int 67 6 H K7 6++7 return 07 Q

/his simple program creates a $ariable named 6, sets the $alue of that $ariable to K, then increments that $alue by one. /his is still not a particularly e(citing piece of code, but it does illustrate the basic structure of a C++ program. /hree statements are e(ecuted, a 0 is returned to indicate that e$erything is )R, and there are brackets surrounding the main function. -f you carefully e(amine this code, and follow this template in all your programming, then

you will do wellD

%eader Files
Header Files:

/here is only one more item that needs to be discussed regarding the basic structure of a C++ program. /hat item is header files. :eader files are files that contain the definitions for functions and<or classes. *asically, if you ha$e a lot of functions or $ariables that you might want to use in se$eral programs, you can put them in a header file, then include that header file anywhere you need to use it.

After creating a header file you can then include a reference to a header file in your program and use the functions and<or classes defined in that header file. /he real intricacies of header files are discussed in a later chapter, in which you will actually create some header files. :owe$er, you should reali9e that there are a lot of these files built into C++ that you can useD 5ell,

%built in' is not e(actly accurate. /hey are actually installed with your compiler and you can include them in your programs./his is demonstrated in the following e(ample.

=include int main!" P return 07 Q

.ou now ha$e access to all the classes and functions defined in the iostream header file. -n the following chapters, you will see se$eral different header files, each pro$iding a different set of functions for you to use. For now, all that is important is that you reali9e that you include a header file using the = sign and the word include. -f the header file is one that is part of C++, then you simply use the .

#ake sure that this is the first thing you do in your fileD Jemember that you use .cpp to indicate a C++ source file and .c to indicate a C source file, while the .h indicates a header source file. A source file is simply a plain te(t file that has the source code for your C++ program. ,ource code is the basic lines of programming language that you write, and that the compiler will later use as a source to create an e(ecutable program.

Fun#tion "asi#s
Function Basics:

5hat are functions8 -n simple terms, a function is a block of code that is identified by some name and can take 9ero or more parameters and can return some $alue. /hat definition probably does little to clarify the issue for youD +ets look at a function and its parts to help clarify this issue. /o begin with, consider the following function, which s1uares a number.

float s1uare!float num" P float answer H num ? num7 return answer7 Q

/he first line of the function is called its declaration line.-t has three parts. /he first part is its return type. /he return type tells you what kind of data the function will gi$e you back. -f it returns nothing, then its return type would be $oid. -n the pre$ious e(ample, the function will return the answer to our math problem, and that is a float. /he second thing is the name of the function. Function names follow the same

guidelines as $ariable names. -t is a good idea to ha$e the function name reflect what the function will do.

3e(t, inside the parenthesis, we ha$e parameters. A parameter is some $alue you pass to the function in order for it to work. For e(ample, in this case, to s1uare a number, we ha$e to gi$e it the number to s1uare. ,tudents often askC %5hat do we need to put as parameters8 4o we e$en need any parameters for this function8' /here is a simple way to answer this 1uestion for any function you write. Ask yourself this 1uestionC -f you wanted some person to do this task for you, would you need to gi$e them anything8 And, if so, what8 -f you wanted a person to s1uare a number for you, you would ha$e to gi$e them that number. :owe$er, if you 6ust wanted them to say hello, you would not ha$e to gi$e them anything. /herefore, a function that s1uares a number should take one parameter, and a function that displays hello on the screen might not take any parameters.

Variabl S#ope
Varia le Scope:

-n the beginning of this chapter, you were introduced

to the concept of $ariables. .ou saw the $arious data types, how to declare a $ariable, and what proper names you could use for $ariables !as well as ones you could not". /here is one more topic concerning $ariables. /his had to be left until after the discussion about the structure of a C++ program, and you will see why shortly. /he topic at hand concerns 5:0J0 you declare a $ariable. /his is called $ariable scope. Consider the following e(ample.

int main!" P int 67 return 07 Q

/his $ariable is declared inside the main function. /hat means it is only usable within that function. -f you create other functions, they will not be able to access the $ariable 6. /his is referred to as a local $ariable. A local $ariable is a $ariable that is declared within a function, or within any block of code. 3ow lets look at another e(ample.

int 67 int main!" P 6++7

return 07 Q

3otice that 6 was 3)/ declared inside the main function. -t was declared outside of any function. /his means that it can be used throughout your code. A $ariable declared outside of any function can be used in any function, and is referred to as a global $ariable. /his is referred to as $ariable scope. ,cope defines the range within which a $ariable can be used. -f the $ariable has local scope, then its range is restricted to the function in which it was declared. -t is essential to pay attention to the scope of your $ariables. -t is not uncommon for a beginner to declare a $ariable inside one function, and then forget that it is only usable within that function.

Chara#ter &rrays
Character !rra"s:

)ne of the most common uses of an array is a character array. A character array is simply a string of characters that makes up one or more words. -t is common to place such input into arrays of characters. +ets look at two e(amples.

Example

,tep 1C 0nter the following code into your fa$orite te(t editor.

=include using namespace std7 int main!" P

char nameT@KS7 cout UU V2lease enter your name OnV7 cin WW name7 cout UU V:ello V UU name UU endl7 return 07 Q

,tep @C Compile and run the program.

/his code is a rather straightforward and practical illustration of how to use arrays, specifically arrays of characters. /here is only one problem. 5e declared the array to hold @K characters. 5hat happens if the user enters B0 characters8 /he answer is that your program may crash.

'sing and Formatting Strings


#sing and Formatting Strings:

.ou ha$e already seen se$eral different $ariable types and we ha$e used them for input and output. /here

is another type of $ariable we ha$e not used yet. /his is the string $ariable. A string is essentially a bunch of characters all together that you can use to store te(t. Gp to this point we simply used an array of characters. .ou can still do this, but now you ha$e other options. 3ow, C++ has a string $ariable that you can use. /o use the string $ariable you will ha$e to include the string header file. :ere is an e(ample.

Example

,tep 1C 0nter the following code into your fa$orite te(t editor.

=include =include using namespace std 7 using stdCCcout7 using stdCCcin7 int main!" P string s H VC++ is sooo cooolD OnV7 cout UU s7 return 07 Q

,tep @C Compile and run the program.

5hen you run this you will see how the string $ariable works. 0ssentially it is an open&ended character array you can use to store string data.

5ith C++, your string functions are defined in the string header file. 0ach string is an ob6ect that has methods

and properties that you can use.Jemember that an ob6ect is a special type of $ariable that has functions associated with it. /hese functions are called methods. /he length property is a commonly used property of strings, which is easy to implement and understand.

"it(ise
Bit$ise %perations:

perations

/he bitwise operators are a bit more difficult to understand than standard operators !pun intended". /he first order of business is to define what a bit is. /he computer ultimately stores e$erything as either a 1 or a 0. A single $alue of either 1 or 0 is called a bit.

0ssentially C++ allows you to work directly with the binary e1ui$alents of numbers, to work with bits. /his is useful in many computer applications, especially in the tele communications industry. .ou will also see these operations in a later chapter when we e(plore basic encryption algorithms. 0(plaining bitwise operations

necessitates first e(plaining binary numbers.

/he numbers you are familiar with in day to day usage are decimal numbers, base 10 numbers. /he base 10 number system is only one possible number system. .ou can use base @, base K, base 1X, or any other base you wish./he reason most human societies ha$e always used base 10 number systems is that we ha$e ten fingers.

/herefore,our ancestors had an easier time counting in tens, thus number systems started out being based on 10. A computer, howe$er, %speaks' in on or off, base @ numbers !also called binary numbers".

For this reason a basic understanding of binary numbers is essential for programming. -n the base @ number system you can only ha$e 0s and 1s. !3otice you dont

actually ha$e any @s, 6ust as the base 10 system only has 0s to Ys." 5hat this means is that after you ha$e placed a 9ero or a one in a particular place, to increase the number you ha$e to mo$e o$er to a new place. /his table might help clarify that a bit.

:opefully you are noticing a pattern here. /he places in any number system are essentially the number systems base raised to some power.

For e(ample, in the base 10 system you ha$e a 1s place, 10s place, 100s place, 1000s place, and so on. -f you think about this for 6ust a moment you should reali9e that 1 is simply 100, 10 is 101, 100 is 10@, 1000 is 10B, and so on. /he same is true for the base @ number system, where you ha$e a 1s place, @s place, Ms place, Is place, 1Xs place, and so on. 1 is simply @0, @ is @1, M is @@, I is @B, 1X is @M, B@ forth. is @K and so

-n computers e$erything is stored in groups of eight bits, called bytes. For this reason all binary numbers are actually represented by an eight&digit series of bits. ,o that one is represented as 00000001, two as 00000010, three as 00000011, and so on.

3ow that you ha$e a basic understanding of what binary numbers are, we can e(plore bitwise operators. *itwise operators work on integers as if they where binary numbers.+ets e(amine the bitwise shift operators first. A bitwise left shift literally shifts all the bits to the eft the specified number of places. Consider the following shift operation. M UU 1

/his means to take the binary e1ui$alent of M !which is 00001000" and shift all the bits o$er 1 space. /his makes the number 00010000. 3otice that this shifts it o$er to an entirely new place, the Is place. ,o operation M UU1 actually yields I. /he right shift operator !WW" simply shifts the numbers to the right rather than the left.

/he other two bitwise operators !> and Z" are of particular use in a $ariety of applications including such di$erse areas as 5indows programming, telecommunication, and encryption, as you will see later in this book.

/he > operators simply asks whether the digits in both numbers are a 1 !and not a 0". For e(ample, M > @ would actually be e$aluated in binary as 00001000 > 000000107 to see how this works, compare them $ertically.

00001000 00000010

.ou can now see that this would yield 0000000,because in neither case do both numbers ha$e a 1 in the same place./o further clarify this point, lets compare two

other numbers, K > B. -n binary this would be the following.

00001001 00000011

/his would yield 00000001 because only in the final place do the two numbers ha$e a 1 in the same

place. /he Z !or" operator asks whether either number has a 1 in that particular place. ,o if you compare K Z B you would ha$e the following.

00001001 00000011

And that would yield 00001011 !which is [ in decimal numbers".

/he \ operator is called the e(clusi$e or, or ])J operator.-t asks if there is a 1 in one of the numbers but not both, at a gi$en place. For e(ample if you consider [ and M and you ])J them you see the following.

00000111 00000100

.ou get 00000011 or B because the ])J operation asks if there is a 1 in the place of one number but 3)/ the other.-n other words, the ])J operation is e(clusi$e to one or the other number, but not both, thus the name. /he following e(ample will allow you to A34, )J, and ])J integers.

Example

,tep 1C 0nter the following code into your fa$orite te(t editor.

=include using namespace std7 int main!" P

int

num1, num@,iand,ior,i(or7

cout UU V0nter an integer OnV7 cin WW num17 cout UU V0nter another integer OnV7 cin WW num@7 iand H num1 > num@7 ior H num1 Z num@7 i(or H num1 \ num@7

cout UU num1 UU V A34 V UU num@ UU V is V UU iand UU endl7 cout UU num1 UU V )J V UU num@ UU V is V UU ior UU endl7 cout UU num1 UU V ])J V UU num@ UU V is V UU i(or UU endl7 return 07 Q

/hese binary operators are going to be of particular importance to you later when you encounter encryption,but they are also used in other types of

programming.-t is also important to understand binary numbers for the simple reason that this is what the computer ultimately translates e$erything you enter into. /he computer only understands binary numbers, so anything you enter into it gets translated into binary.

Variabl S#ope
Varia le Scope:

-n the beginning of this chapter, you were introduced to the concept of $ariables. .ou saw the $arious data types, how to declare a $ariable, and what proper names you could use for $ariables !as well as ones you could not". /here is one more topic concerning $ariables. /his had to be left until after the discussion about the structure of a C++ program, and you will see why shortly. /he topic at hand concerns 5:0J0 you declare a $ariable. /his is called $ariable scope. Consider the following e(ample.

int main!" P int 67 return 07 Q

/his $ariable is declared inside the main function. /hat means it is only usable within that function. -f you create other functions, they will not be able to access the $ariable 6. /his is referred to as a local $ariable. A local $ariable is a $ariable that is declared within a function, or within any block of code. 3ow lets look at another e(ample.

int 67 int main!" P

6++7 return 07 Q

3otice that 6 was 3)/ declared inside the main function. -t was declared outside of any function. /his means that it can be used throughout your code. A $ariable declared outside of any function can be used in any function, and is referred to as a global $ariable. /his is referred to as $ariable scope. ,cope defines the range within which a $ariable can be used. -f the $ariable has local scope, then its range is restricted to the function in which it was declared. -t is essential to pay attention to the scope of your $ariables. -t is not uncommon for a beginner to declare a $ariable inside one function, and then forget that it is only usable within that function.

"asi# Stru#ture o$ Fun#tions


Basic Structure of Functions:

/he first item to address is to e(plain e(actly what a function is. A function is essentially a block of code that can be called by name, may be passed parameters, and may return a $alue. Another way to put that would be to say that a function is a group of related

statements<e(pressions that work together to accomplish some goal and are grouped under a common name. +ets take a look at the main function that all C and C++ programs must ha$e. *y issecting it, you may get a better idea of what a function is and how one is built.

int main!" P return 07 Q

/he first line is called the function declaration line.-t contains three ma6or parts. /hose parts are the return type, name, and parameter list. /he return type simply tells you what kind of data this function will return. )ne way to think of it is to reali9e that you create functions to perform some goal.

5hate$er answer is generated from that function is what is returned. -f you create a function to compute the area of a circle,

then the return $alue would be the actual area

computed.

/he return type for most functions can be any $alid data type. -t can be an int, float, bool, long, and so on. :owe$er, the main function must return an int. -f the function does not return anything at all, then its return type is %$oid.'

Creating and Calling Fun#tions


Creating and Calling Functions:

)b$iously you could simply put e$erything into the main function and it would, indeed, compile and run, but this would 1uickly become unwieldy. -n fact, your program would certainly become completely unmanageable and unreadable by the time it e$en reached a few do9en lines of code. Fortunately you dont ha$e to do that. .ou can create separate functions to handle these other items. /here are a few idiosyncrasies regarding function creation in C++. /he following list summari9es the re1uirements.

1.

/he function must ha$e a return type. -t may

be $oid if the function returns nothing.

@.

/he function must ha$e a $alid name.

B.

/he function must ha$e parentheses for a list of parameters past to it, e$en if the parentheses are empty.

M.

/he function must either be written before its called, or it must be prototyped.

/he first three you already know about, but he fourth rule may sound 1uite confusing. 5hat does it mean to prototype a function8 0ssentially the problem is that the C++ compiler cannot call a function it does not know about. .ou ha$e to let the compiler know what that function is and what it does before you can call it.)ne way to do this is to make sure you write out the function in your file, before you call it. /his 1uickly becomes 1uite cumbersome.

/herefore, C++ pro$ides another way to do this. /hat method is prototyping. All you do to prototype a function is to write its declaration line at the beginning of the source file

Fun#tion
Function %&erloading:

verloading

C++ pro$ides you with a powerful toolLo$erloading. you can o$erload a function so that the same name is shared by more than one function, but each function performs a different action. Function o$erloading is essentially when you ha$e more than one function with the same name,but each performs different arguments. /he first 1uestion that comes to your mind is probablyC 5hy would you want to o$erload a function8 /here are se$eral cases in which you may want to do this. For e(ample, if you wanted to do an operation on some input, but the input came in different forms. /he input might be an integer $alue or a floating point decimal $alue. .ou could o$erload the function in 1uestion, and ha$e one $ersion take an integer argument and the other a float argument.

!assing Values by )e$eren#e


Passing Values " 'eference:

5hen you pass a $alue to a function you are really copying the contents of one $ariable to another $ariableL theother $ariable is the parameter of a function. /his means the parameter is, essentially, a copy of the $ariable that was passed to the function. /his means that you are not changing the $alue of the $ariable that is outside the

function. /hat might sound confusing, so lets look at an e(ample that illustrates this concept.

Example

,tep 1C 2lace the following code into your fa$orite te(t editor.

=include using namespace std7 $oid demo!float"7 int main !" P float num17 cout UU V2lease enter a number. OnV7 cin WW num17 cout UU V*efore the demo function your number is V UU num1 UU VOnV7 demo!num1"7 cout UU VAfter the demo function your number is

stillV UU num1 UU VOnV7 return 07 Q $oid demo!float number" P number H number ? M7 cout UU V-nside the demo function the number is now V UU number UU VOnV7 Q

,tep @C Compile this code.

,tep BC Jun the code

As you can see from this e(ample, what occurs inside the function has no bearing on the $alues of the $ariables outside the program. 5hen you call the demo function, you take the $alue that is in num1 and place that $alue in the function parameter number.

3umber is an entirely new $ariable occupying its own space in memory and is separate from num1. /his is called passing a $ariable by $alue. -t is the standard way that $ariables are passed in C++ !as well as in ;a$a and se$eral other languages".

/here is another way to pass a $ariable. /hat is by reference. 5hen you pass by reference you dont simply copy the $alue of some $ariable to a parameter. 5hat you pass is a reference to the $ariables address in memory. 5hat that means is that the parameter of the function is 3)/ a new $ariable. -t is simply a $ariable. *oth new name for the

the $ariable name and the parameter name

refer to the same place in memory, they refer to the same $alue. .ou accomplish this by simply adding the > or address of operator to your function parameter. /he > means address of and it refers to the address in memory.

"uilt*in Fun#tions
Built(in Functions:

-n addition to the $arious functions you can create, C++ includes some useful functions you can use. Actually the term built&in is not e(actly accurate, but it is close enough./hese are functions that can be included in your program and then use. -n fact, there are 1uite a few such functions. /his book will show you some of the most commonly used functions and also show you some e(amples of how to use these functions.A few of the more commonly used functions are summari9ed in /able

Fun#tion

!urpose This function copies whatever is in the source #often an array or structure to the destination. The si'e tells you how much to copy. To use this function you must either include the memory or string header files.

void Fmemcpy#Fdestination, Fsource, si'e/@

This function sets the destination to the character shown in replacement. This is void F memset#Fdestination, replacement, si'e/ often used to set an array to all 'eros. To use this function you must either include the memory or string header files. charF itoa# int value, charF buffer, int radix / 7oteQ This one is 76T (7K* Ktandard C++ but is )uite commonly used and supported by most C++ compilers. int atoi# const char Fstring/@ This takes an integer and returns the character e)uivalent. The radix is the base of the integer you are converting it from #base ,, base D0, etc./. This takes an integer and returns the character e)uivalent. The radix is the base of the integer you are converting it from #base ,, base D0, etc./. Converts the character to lowercase. You must include the string header file for this function. Converts the character to uppercase. You must include the string header file for this function.

int tolower# int c /@

int toupper# int c /@

:intD memcpy and memset are fre1uently used with structures./hey can, howe$er, also be used with arrays.

/he memcpy function shown in /able is used to copy comple( data types, such as arrays and structures, from one location in memory to another. .ou cannot simply copy one array to another as you would copy a standard $ariable. /he following

is an e(ample.

int (,y7 ( H M y H (

/his works fine, and the contents of ( are copied to y. :owe$er, this does not work with arrays.

int (T10S H P@,M,1,X,X,Y,0,11,1,@Q7 int yT10S7 y H (7

/his will not work. -t will generate a compiler error.,o how do you copy one array to another8 /hat is where memcpy comes in. /o use memcpy, you must first include the memory header file.

=include =include using namespace std7 int main!" P int (T10S H P1,@,B,M,K,X,[,I,Y,0Q7 int yT10S7 memcpy!y,(,10"7

return 07 Q

/he function copies items from the second parameter to the first parameter, from the source to the destination. -t copies the number of bytes you indicate in the third parameter, the si9e parameter.

Necision Ktructures and <oops


Introdu#tion
)ntroduction:

*y now you should ha$e a firm grasp of essentially what C++ is, and know how to create a $ariable, use functions, and write some simple C++ programs. 3ow its time to add to that knowledge, and e(pand your programming skill&set. /his chapter will introduce you to decision structures and loops. /hese are key concepts that e(ist in all programming languages7 it is 6ust their implementation that is somewhat different. -n this chapter, you will learn how to ha$e your code branch in different directions based on certain criteria. .ou will also learn how to ha$e your code loop repeatedly.

A decision structure is a block of code that branches, depending on some decision. /here are many times when you will need different code to e(ecute, depending on some criteria such as user input. .ou ha$e probably used programs in which you were asked to pro$ide some input, maybe a simple yes or no. /he program beha$ed differently based on the input you ga$e it. /his is an e(ample of a decision structure. 4ifferent blocks of code are e(ecuted differently based on some criteria.0ssentially a decision structure is code that lets your code branch based on some criteria.

#ost programs are simply combinations of decisions. -f the user does this, then the program responds with one action. -f the user does something else, then the program responds with a different action. /he entire acti$ity of data processing is dominated by decisions. For this reason, decision structures are a key programming concept found in all programming languages.

I$ Statements
)f Statements:

/he most common type of decision structure is the if statement. /hese e(ist in all programming languages but are implemented slightly differently. An if statement literally says, %if some condition e(ists, then do this certain code.' A generic, programming&language&neutral e(ample would be the following.

-f some condition e(ists 0(ecute this code

/he condition is usually the $alue of some $ariable.-f a particular $ariable contains a certain $alue, or e$ena range of $alues, then e(ecute a gi$en block of code. -t is important to recall that if statements are a common facet of almost all programming languages. :owe$er, you should know that many languages use synta( that is similar to the synta( of C++. -n fact, if statements in C, ;a$a, and ;a$a,cript are almost indistinguishable from if statements in C++. /his is important for you to reali9e. /he more thoroughly you master the C++ programming language, the easier it will be for you to learn these other programming languages at some future data, should you so desire.

+ets look at how you implement if statements in C++. :ere is a basic e(ample that we can dissect to help you learn about if statements.

-f! age HH 1X" P cout UU V.ahoo... .our old enough to dri$eDOnV7 Q

+ets take a look at this code because there are se$eral

things you should note. First of all, you ha$e the word if followed by parentheses. -nside the parentheses is where you locate the condition that you base your if&statement on. -n other words, if !whate$er is in theparentheses is true" do the stuff in the following brackets. /he brackets, recall from our discussion of functions, are 6ust boundaries around any block of code. /he code in these brackets is what you wish to e(ecute if the statement in the parentheses is true. Finally, notice that there is a double e1uals sign in the parentheses.

S(it#h Statements
S$itch Statements:

if statements and if&else statements are great if you ha$e one or two choices. *ut what happens when you ha$e se$eral choices8 .ou can still use a series of if&else statements, but that 1uickly becomes cumbersome.Fortunately, there is another choiceLthe switch statement.A switch statement is literally saying, %switch the path you take through the code based on the $alue of some $ariable.' A switch can only be one on a single character or on an integer $alue. .ou can also think of a switch statement as a comple( $ersion of the if statement. -ts a way of using if statements when there are

multiple possible choices.

,witch statements, like if statements, e(ist in most programming languages and the structure is the same.

/he implementation of the switch statement in C++ is relati$ely straightforward. +ets take a look at an e(ample in the following code segment.

int choice switch !choice" P case 1C cout UU V.ou chose 1 OnV7 break7 case @C cout UU V.ou chose @ OnV7 break7 case BC cout UU V.ou chose B OnV7 break7 defaultC cout UU V.ou made an in$alid choice OnV7 break7 Q

-f you e(amine this code, you will notice se$eral things. First, you will notice the brackets. /he brackets start right after the switch statement and end after the last statement in the switch. A switch statement is a code block, 6ust like an entire function or an if statement. And remember that all code blocks are bounded by brackets. .ou should also notice that each case has a number then a colon. 5hat the code is literally saying is %if it is the case that the integer choice is e1ual to one, then e(ecute this code.' At the end of each case, there is a break statement. /his is $ery important. 5ithout it, the code will continue to e(ecute and will run the ne(t case statement as well. Finally, we ha$e a default statement. -f the $ariable we are switching on does not match any of our cases, then the default will occur.

-t is sometimes helpful to think of a switch statement like a switch on a railroad track. .ou will

switch the direction you tra$el through the code, based on the $alue of the $ariable you ha$e selected to base your switch on. +ike if statements, the switch is common to most programming languages, 6ust its implementation is different.

For +oops
For *oops:

/he for loop is perhaps the most commonly encountered loop in all programming. -ts structure is the same in all programming languages, only its implementation is different. -t is 1uite useful when you need to repeatedly e(ecute a code segment,a certain number of times. /he concept is simple. .ou tell the loop where to start, when to stop, and how much to increase its counter by each loop.

/he essence of the for loop is in the counter $ariable. -t is set to some initial $alue, it is incremented !or decremented" each time the loop e(ecutes. 0ither before or after each e(ecution of the loop the counter is checked. -f it reaches the cut&off $alue, stop running the loop.

/he specific implementation of the for loop in C++ is shown hereC

for !int i H 07 i U K7 i++" P Q

5hat this code is doing is rather straightforward.First, we create an integer to be used as a loop counter to count how many times the loop has e(ecuted" and we gi$e it an initial $alue

of 9ero. 5e then set the conditions under which the loop should e(ecute. /hats the i U K portion of the code. -t is essentially saying, %keep going as long as i is less than K.'As soon as that condition is nolonger true !i.e., i is e1ual to K or greater than K", the loop stops e(ecuting. Finally, we ha$e a statement to increment the loop counter after each iteration of the loop. 3otice the semicolons in the for loop declaration. .ou should recall that all statements< e(pressions in C++ end with a semicolon.

/hese code snippets are, indeed, $alid statements and could be written as stand&alone e(pressions. /he reason the last one does not ha$e a semicolon is because it is followed by a closing parentheses and that terminates the e(pression. /he three parts to the for loop declaration are the following.

1.

4eclare and initiali9e the loop counter.

@.

,et the conditions under which the loop will e(ecute.

B.

-ncrement the loop counter.

Do +oops
+o *oops:

/he for loop is the most common type of loop7howe$er, it is not the only type of loop. /here are other loop structures you can use, although they all accomplish the basic goal of e(ecuting a gi$en pieceof code a specified number of times. /he do loop is one such loop structure. Gnlike the for loop, howe$er, it does not e$aluate whether or not the loop should continue until after the loop has completed an iteration. /he following is the generic structure.

4o P << place code here Q while !some condition is true"

/he

following is a more specific e(ample.

Example ,-,

,tep 1C

=include using namespace std7 int main!" P int (7

do P coutUU ( (++7 Qwhile !( U 10"7 return 07 Q 7

.ou can see that the do loop does essentially the same thing as the for loop. :owe$er, the loop condition is not e$aluated until after the loop has e(ecuted an iteration, and the loop counter is incremented inside the loop. /hese loop structures gi$e you different options for accomplishing the same basic goal.

While +oops
While *oops:

5hile loops are almost identical to do loops./hey are simply structured a little bit differently./he do loop has the condition to be e$aluated at the end of the loop, whereas the while loop has it at the beginning.

while!condition" P

$xception !andling
Introdu#tion
)ntroduction:

-n any programming situation $arious problems can occur. .ou can ha$e basic errors of many types. :andling those problems is of paramount importance.

.ou do not want your program to crash when an error occurs. -f this were to occur, the people using your software !programmers generally refer to them as %users'" would be $ery unsatisfied with your product.

A better idea is to correct the

problem or at least gi$e the user a friendly message telling them what has occurred. 0(ception handling is, therefore, a critical topic in programming.

4ifferent programmers ha$e different philosophies regarding e(ception handling. :owe$er, it is commonly belie$ed that you cannot ha$e too much e(ception handling. Code should be contained inside some e(ception handling.

Errors and Ex#eptions


Errors and Exceptions:

/here is an almost limitless list of things that can go wrong. 5hat would happen if you tried to open a file that wasnt there8 .ou would get an error, and without error handling your program would crash. 5hat if you asked a user to enter a number and they typed in their name, then your code tried to store their input in an integer $ariable8

.ou would get an error, and, yes, without error handling your program would crash.

0rrors can be grouped into three main categories, each of which is described in /able .

Error Type

Des#ription ( syntax error occurs when you have attempted to use the language in a way that is inappropriate. "or example if you said Hif #x > > y/I when you meant to write Hif #xAAy/I that would be a syntax error. The compiler will not compile your code if you have any syntax errors. This is an error that occurs when you run your program. *t is any interruption to the normal flow of your application. Trying to open a file that does not exist and dividing by 0 are two examples of runtime errors. These errors are also called exceptions. This occurs when your program compiles and runs properly, but produces erroneous results. There is some error in your programming logic. This can be the hardest type of error to find and is what is generally referred to as a Hbug.I

Kyntax

Muntime

<ogic

try-catch Blocks
tr"(catch Bloc.s

C++ offers a rather powerful error &handling tool called the try&catch block. /his techni1ue is also used in ;a$a and *.netE, so this is a skill you will be able to carry o$er to other programming

languages.

/he try&catch block consists of two sections. /he first is the code that you want to e(ecute. /his is the code that you try. -f an e(ception is generated then the catch block catches it. /hus, the catch block is where your error handling goes.

Throwing Exceptions
Thro$ing Exceptions

-n addition to catching e(ceptions, you can simply throw them. /hrowing an e(ception simply sends the e(ception back to the function that called the current function, so that the pre$ious function can handle the e(ception. /he following e(ample illustrates this.

Example /-0

,tep 1C 0nter the following code in your fa$orite te(t editor.

=include using namespace std7 << function prototypes. float di$ideAnumber!float , float"7 int main!" P float di$idend,di$isor,answer7 try P cout UU V2lease enter a number OnV7 cin WW di$idend7 cout UU V2lease enter a number OnV7 cin WW di$isor7 answer H di$ideAnumber!di$idend,di$isor"7 cout UU di$idend UU V di$ided by V7 cout UU di$isor UU V is V UU answer7 Q<< end of try catch!..." P cout UU Voops, there is an errorDV7 Q<< end of catch return 07 Q float di$ideAnumber!float num1, float num@" P try

P float answer7 answer H num1<num@7 return answer7 Q catch!..." P throw7 Q<<end of catch

,tep @C Compile the code.

.ou can see that e(ceptions are not handled in the $arious functions, only in the main function. some programmers prefer to centrali9e their error handling in this way.

Saving Errors to Logs


Sa&ing Errors to *ogs

,ometimes it is simply not helpful to display error messages to the user. -f the error is not critical, its more likely to simply confuse your end user without accomplishing anything useful. -n fact, it is not prudent to display all messages to the user.

)ne answer to this is to simply log the error messages to a flat file. +ater, support personnel can read the log and see what has been occurring and perhaps diagnose what is wrong. .ou can e$en combine a message to the user with a log entry if you wish.

5ser-Nefined Nata Types


Stru#tures
Structures:

A structure is really 6ust a compound data type. -ts a way of grouping se$eral related $ariables under a common $ariable name. For e(ample, if you were writing a program that in$ol$ed employee data, you would ha$e se$eral indi$idual pieces of data to store regarding a gi$en employee. .ou would ha$e a last name, first name, salary, and so on. -f you place all that data into separate $ariables, it may become difficult to keep track of e$erything as your program grows in comple(ity. 5hich $ariables in your program are rele$ant to employee data and which are related to something else8 /his will become an e$en worse problem when you consider that other parts of your program might need similar data. For e(ample, you would also need to store customer data, which would also ha$e fields such as last name. 5hich last name goes with employees and

which with customers8 A structure pro$ides you a fairly easy way to group all the data together. /he following e(ample illustrates a generic definition of a structure, and a specific one.

1eneric example:

struct structname P $artype $arone7 $artype $artwo7 Q7

Specific example:

struct employee P char lastnameTB0S7 char firstname TB0S7 float salary7 Q7

)nce you ha$e defined a structure you can then declare a $ariable of that structure type anywhere you wish. .ou create an instance of this data type 6ust like you would create an instance of one of C++s standard data types.

.ou ha$e the data type name followed by some name you wish to gi$e your $ariable. ;ust like all $ariables, you ha$e allocated a space in memory set aside to hold data of a certain type. /he space you allocated depends on the si9e of your structure. .ou determine the si9e of a structure by totaling all of the indi$idual data types. For e(ample, if

your structure contains two ints and one char, then it will be @ ? !four bytes per int + 1 byte for the character H Y bytes".

employee myemployee7

you can then access the elements of the structure by using the name of the structure $ariable you created followed by a period and then the name of the element of the structure you wish to access.

myemployee.salary H M0000.MM

As you can see, the structure definition is rather simple. /he keyword struct is followed with the name of the structure. /hat name can be any $alid C++ name, 6ust as you would name any other $ariable. .ou then ha$e brackets that define the boundaries of the structure. *ecause structures are often used in se$eral places in a program, they are often defined in a header file. .ou can then simply include that header file

in any source file where you wish to use the structure.

Typede$s
T"pedefs:

A structure is only one way that you can define your own types of $ariables in C++, the typedef is another. A typedef in C++ is a type of $ariable declaration. /he purpose of the typedef is to create new types from e(isting data types. *ecause a typedef is simply a declaration, it can be intermingled with standard $ariable declarations. :owe$er, it is common practice to declare all typedefs before declaring the standard $ariables. -t is also common practice to capitali9e the first letter of a typedef to distinguish it from the built&in types, which all ha$e lowercase names. /ypedefs are often used to create synonyms for built&in types.

typedef int -nteger7 <</he word F-ntegerF can now be << used in place of int int k,6 << this creates two ints

-nteger m,n7 << this also creates two ints

-n this e(ample, a typedef was used to substitute for a built&in type./his is generally not recommended. 5hy not 6ust use the built&intype8 :owe$er, because it is used in code you may see, it is important for you to see this application of typedef.

Gsually, a typedef associates a type name with a more c complicated typespecification. /ypedefs are often used with arrays. A typedefshould always be used in situations where the same typedefinition is used more than once for the same purpose.

typedef int myarrayT10S7 <<10 integers myarray a,b7 << /his creates two arrays int (T10S, yT10S7 <</his does the same thing without <<typedef

*asically, the typedef is a way for you to create your own new labels for data types. .ou can use it with any data type, e$en as a synonym for an e(isting basic type such as int. -t is recommended that you only use it with more comple( data types such as an array. /ypedefs can e$en be used for other types you create such as structures.

'nions
#nions:

,o far we ha$e looked at structures and typedefs as e(amples of user&defined types. /here are still more user&defined types to e(amine. /he one we will e(amine ne(t is the union. A union allows you to handle an area of memory

that could contain different types of $ariables. /he synta( for unions is identical to that for structures. .ou can e$en contain unions within structures, or $ice $ersa. /he following is an e(ample of a union data type.

union 3umeric/ype

<< 4eclare a union that can hold

<< the followingC P inti alue7 long l alue7 double d alue7 Q7 << int $alue << long $alue << double $alue

-f you think about it, the reason these data types are called unions is that they are the union of se$eral different data types. /he following is an e(ample using a union.

Example 2-3

,tep 1C 0nter the following code into your fa$orite te(t editor.

=include using namespace std7 union 3umeric/ype << 4eclare a union that can

<< hold the followingC P

inti alue7 long l alue7

<< int $alue << long $alue << double $alue

double d alue7 Q7 int main!" P 3umeric/ype $alues7

cout UU V2lease enter a number OnV7 cin WW $alues.d alue7 cout UU V2lease enter another number OnV7 cin WW $alues.l alue7 cout UU $alues.d alue7 cout UU V OnV7 cout UU $alues.l alue7 cout UU Vpress any key to continueOnV7

return 07 Q

,tep @C Compile your code.

,tep BC Jun your code

Enumerations
Enumerations:

3ow you ha$e seen structures, typedefs, and unions. /he ne(t category of user&defined data type is the enumeration. An enumeration is a user&defined type that defines named constants. 0numerations are declared using the enum keyword. An enumeration is really a set of named integer constants that specify all the $alues that $ariables of this type may ha$e. 3ote that these are named integer constants. /hat means that we gi$e names to integer $alues.

/he enumerated type is declared using the following form.

enum typename Penumeration listQ7

enum is a C++ keyword. /he compiler sees this word and knows that the definition for an enumeration is coming up. /he word typename can be any $alid C++ name identifier. /he enumerated list is a comma&delimited list of the items in the enumeration, enclosed in brackets, and terminated by a semicolon. /he following is a generic e(ample.

enum testP$alue1,$alue@,$alueBQ7

"it Fields
Bit Fields:

#any of the user&defined data types we ha$e e(amined so far are a$ailable, in one form or another, in other programming languages such as ;a$a and isual *asic. :owe$er, C++ offers one

intriguing user&defined type that is not present in most languages. /hat type is the bit field. 3ormally, in any programming language, any $ariable is of some particular data type !int, float, bool, etc." andtakes up a certain number of bytes !remember that there are eight bits in a byte". :owe$er, C++ allows you to access indi$idual bits. /his is of particular importance when writing software that communicates with hardware, and in the telecommunications industry.

5hen you create a bit field, you create it like you would any normal structure. :owe$er, each indi$idual element of the structure is declared as an unsigned, then gi$en a name and a colon. After the colon is a number representing how many bits this particular element occupies.

-t is beyond the scope of this book to e(plore either hardware programming or telecommunications programming. :owe$er,both of these areas of software de$elopment make e(tensi$euse of the C++ programming language, and of features suchas bit fields. /he following e(ample should help illustrate the basics of using a bit field. Although the e(ample is about checking the status of a serial line and taking appropriate action, the specific code for the particular actions to takeis beyond the scope of this book

and, therefore, the functions called are empty, with 6ust comments in them. /he studious reader can easily find appropriate serial line code e(amples onthe -nternet and e(pand this e(ample. )ur interest now is simplyto study the bit field itself, not its potential applications.

Example 2-/

,tep 1C 0nter the following code into your fa$orite te(t editor.

=include using namespace std7 << declare a bit field struct status P unsigned changeinlineC 17 unsigned cleartosendC17 unsigned inacti$eC17 unsigned ringingC17 unsigned signalrecei$edC17 Q7 << function prototypes $oid dialnumber!"7 $oid answerphone!"7 $oid senddata!"7 int main!"

P << delcare an instance << of the bit&field status linestatus7 if !linestatus.cleartosend" senddata!"7 if !linestatus.inacti$e" dialnumber!"7

if!linestatus.ringing" answerphone!"7 return 07 Q $oid dialnumber!" P << place code here to dial Q $oid answerphone!" P << place code here to answer the phone Q $oid senddata!" P << place code here to send the data Q

,tep @C Compile that code.

/he important thing to reali9e is that the bit field allows you to directly speak the same language as 2C hardware, and telecommunications lines. /hese de$ices do not send data in types such as int, long, or double. /hey send a stream of indi$idual bits. C++ allows you to directly work with those indi$idual bits in a way that few other languages do.

!ointers Introdu#tion
Pointers )ntroduction:

2ointers are a powerful, but troublesome part of C and C++. #ost beginning C<C++ programmers ha$e significant trouble understanding and appropriately using pointers, so please pay close attention to this chapter. /he first, and most ob$ious 1uestion, is what, indeed, is a pointer8 /his 1uestion is probably foremost in your mind at this particular point in time.

A pointer is a special type of $ariable, one that literally points to an address in memory of another $ariable. -f you think about standard $ariables,

they are labels used to identify small segments of memory set aside to hold data of a particular type.

A pointer simply points to the segment of memory occupied by another $ariable. 5hereas a standard $ariable holds a $alue, the $alue stored at an address in memory, a pointer simply holds the address of another $ariable. .ou probably noticed that this paragraph pro$ided three different but similar definitions for the pointer. All three of these definitions say the same thing, but in slightly different ways. -t is hoped that one of these definitions will strike a chord with you andyou will comprehend the concept.

!ointer "asi#s
Pointer Basics:

As pre$iously stated, a $ariable is a small section in memory set aside to hold data of a specific type. 5hen you writeC

int 67

you ha$e 6ust set aside M bytes of memory and you

are referring to that M bytes by the $ariable 6. /he $ariable 6 represents whate$er $alue is currently stored in those M bytes of memory.

4eclaring a pointer is almost the same. .ou still declare a data type, 6ust as you do with standard $ariables7 howe$er, you must add the asterisk !?" symbol to denote that it is a pointer. .ou can place the asterisk immediately after the data type, or before the $ariable name. 0ither method is a $alid way of declaring a pointer $ariable. For e(ample, both of the following are $alid pointer declarations.

int? k7 int ?k7

/he asterisk!?" is called a reference operator. /his name makes perfect sense, because it, indeed, is a reference to an address in memory. /he ? operator can be literally translated to %the address pointed at by,' /he way you use a pointer is that you ha$e it set e1ual to the address of another $ariable. +ets look at the following e(amples.

int 67 int ?kC k H >67

3ow the pointer k represents the address of 6. #ore specifically it is pointing to the first byte of the M bytes that 6 occupies.

/his is important to remember for se$eral reasons. /he first being that if you print&out 6 you will get a numeric $alue. :owe$er, if you print&out k you will get a rather long number that represents an address in memory.

!ointer
Pointer %perations:

perations

*ecause a pointer is actually an address in memory, rather than a $alue, it should make sense to you that normal operations on a pointer beha$e 1uite differently. For e(ample, with a normal $ariable if you use the increment operator on it !++", you increase its $alue by one. 5ith a pointer, you actually mo$e the pointer o$er a number of bytes e1ual to the si9e of the data type. *ecause an integer is M bytes !at least on @&bit operating systems", if you ha$e an integer pointer and do the increment operation, then it will mo$e the pointer o$er M bytes in memory. ,o, fore(ample, if you mo$e an int pointer o$er M bytes, it will no longer be pointing at that same int. -t will ha$e mo$ed past the M bytes occupied

by the int $ariable and will be pointing at some space in memory, the contents of which are not known.

Watchout4

-f you mo$e your pointer to some unknown memory location and then do some operation on it, you might be interfering with the operationsof some other program on your 2C, including the operating system.

/o conduct arithmetical operations on pointers is somewhat differentthan to conduct operations on other data types. /o begin with, you can only use addition !+", subtraction !&", increment !++", and decrement !L" operators. .ou cannot use multiplication or di$ision on a pointer. *ecause a pointer contains an address in memory, multiplication and di$ision do not make sense.

A pointer holds an address, if you multiply that by M, you get a number that may representmore memory that your computer e$en has. *ut both addition and subtraction ha$e a different beha$ior with pointers then they do withnormal data types. /he addition operator causes the pointer to mo$ea certain number of bytes to the right. /he subtraction operator causesthe pointer to mo$e a certain number of bytes to the left. /he numberof bytes mo$ed is the numbe r used in the e(pression times the si9e of the data type.

Consider the follo$ing code-

int a7 int ?p7 p H >a7 p Hp+@7

5hat actually happens in the fourth line is that the pointer mo$es o$er bytes. -t is not adding @ to the $alue of a. -t is, instead, pointing to the last @ bytes of the integer a

!ointers to !ointers
Pointers to Pointers:

,o far we ha$e simply looked at pointers to standard $ariables. :owe$er, C++ also allows the use of pointers that point to other pointers. A pointer to a pointer is often referred to as multiple indirection. *ecause a pointer is simply an indirect method of accessing a $ariable, then a pointer to a pointer would be multiple indirection. /o create a pointer to a pointer, we only need to

add an asterisk !?" for each le$el of reference.

char (7 char ? y7 char ?? 97 ( H FaF7 y H >(7 9 H >y7

/he truth is that you can program for years and ne$er ha$e a particularly compelling need to implement pointers to pointers.

!ointers to Fun#tions
Pointers to Functions:

C++ also allows another type of pointer7 this one is more useful than pointers to pointers. C++ allows you to create pointers to functions. /he greater utility of this is for passing a function as a parameter to another function. /hat means you can pass an entire function as an argument for another function. /o declare a pointer to a function we must declare it like the prototype of the function, but

enclosing between parenthesis !" the name of the function and then placing a pointer asterisk !?" before the name of the function.

<< pointer to functions =include using namespace std7 << function prototypes int subtraction !int a, int b"7 int addition !int a, int b"7 <<function pointer prototypes int !?minus"!int,int" H subtraction7 int operation !int (, int y, int !?functocall"!int,int"" P int i7 i H !?functocall"!(,y"7 return !i"7 Q int main !" P int m,n7 m H operation !K, K, addition"7 n H operation !K0, m, minus"7 cout UU n7 return 07 Q int addition !int a, int b"

P int answer7 answerHa + b7 return answer7 Q int subtraction !int a, int b" P int answer7 answer H a & b7 return answer7 Q

-n the e(ample, the word minus is used as a pointer to a function that has two parameters of type int. .ou can now pass that functions pointer to another function.

int !? minus"!int,int" H subtraction7

-n this case, you pass the functions pointer to a function called operation, which will do whate$er function is passed to it !be it addition or subtraction". /his is a rather powerful feature that C++ pro$ides you.

!ointers to Stru#tures
Pointers to Structures:

As you ha$e probably seen, we can use a pointer to any data type, or e$en to a function. -f you think about this for 6ust a moment it makes sense. 0$erything in your program is loaded into memory. Apointer is simply an indicator of an address in memory. .our $ariablesare places in memory, other pointers are referencing a place in memory, and functions are loaded in memory. *ecause all this is at some location in memory, it makes sense that you should be ble to ha$e a pointer$ariable that references that location in memory.

*ecause a structure is a comple( data type, you can also ha$e a pointer to a structure $ariable. -n fact, pointers to structures area commonly used techni1ue. A pointer to a structure allows you to point to that space in memory, 6ust as you would point to any other $ariables space in memory.

/here is one slight change when dealing with pointers to structures. 3ormally you access an element of a structure by gi$ing the structure name, a !.", then the name of the element. For pointers to structures you must use a &W rather than a pointer.

!ointers Introdu#tion
Pointers )ntroduction:

/here is one last, but critical issue to address regarding pointers. *efore you use a pointer you must initiali9e it. .ou initiali9e a pointer in oneof two ways. /he most common way is to set the pointer e1ual to the addressof some standard $ariable. 5ith pointers to standard $ariable types you canalso set the pointer e1ual to 0, as in the following e(ample.

int ?ptr H 07

-f you attempt to utili9e a pointer that has not been initiali9ed, by one method or the other, then you will generate an e(ception and probably crash your program. *ecause a pointer is a reference to an address in memory, if you dont initiali9e it then it is pointing to some indeterminate address in memory. /he following short e(ample illustrates what happens when you use a pointer that has not been initiali9ed.

Example

,tep 1C /ype the following code into your fa$orite te(t editor.

=include using namespace std7 struct account P int accountnum7 float balance7 float interestrate7 Q7 int main!" P account myaccount7 account ?ptraccount7 ptraccount&Wbalance H 10007 return 07 Q

,tep @C Compile that code.

,tep BC Jun the code

You might also like