Download c++ notes explaining and guiding programmers and more Thesis Computer Science in PDF only on Docsity!
``Table of Contents
- 2 Your first C++ program.........................................................................................................
- 2.1 Using the iostreams class
- 3 Namespaces...........................................................................................................................
- 4 Fundamentals of program structure
- 4.1 "Hello, world!"
- 5 Comments.............................................................................................................................
- 6 Variables. Data Types............................................................................................................
- 6.1 Identifiers..............................................................................................................................
- 6.2 Fundamental data types.........................................................................................................
- 7 Introducing strings
- 8 Scope of variables.................................................................................................................
- 8.1 Initialization of variables......................................................................................................
- 9 Specifying storage allocation................................................................................................
- 9.1 Global variables....................................................................................................................
- 9.2 Local variables......................................................................................................................
- 9.2.1 Register variables..................................................................................................................
- 9.3 static......................................................................................................................................
- 9.4 extern.....................................................................................................................................
- 9.4.1 Linkage..................................................................................................................................
- 9.5 Constants...............................................................................................................................
- 9.5.1 Constant values.....................................................................................................................
- 9.6 volatile...................................................................................................................................
- 9.7 Literals..................................................................................................................................
- 9.7.1 Integer Numerals...................................................................................................................
- 9.7.2 Floating Point Numbers........................................................................................................
- 9.7.3 Character and string literals..................................................................................................
- 9.7.4 Boolean literals.....................................................................................................................
- 9.8 Defined constants (#define)..................................................................................................
- 9.9 Declared constants (const)....................................................................................................
- 9.11 String Stream.........................................................................................................................
- 2 Example................................................................................................................................
- 3 #include "stdafx.h"................................................................................................................
- 4 #include ..............................................................................................................
- 5 #include ..................................................................................................................
- 6 using namespace std;.............................................................................................................
- 7 int main ()..............................................................................................................................
- 8 {.............................................................................................................................................
- 9 string mystr;........................................................................................................................
- 10 cout << "What's your name? ";...........................................................................................
- 11 getline (cin, mystr);.............................................................................................................
- 12 cout << "Hello " << mystr << ".\n";....................................................................................
- 13 cout << "What is your favorite team? ";.............................................................................
- 14 getline (cin, mystr);.............................................................................................................
- 15 cout << "I like " << mystr << " too!\n";..............................................................................
- 16 return 0;...............................................................................................................................
- 17 }.............................................................................................................................................
- 1 Operators...............................................................................................................................
- 1.1 Booleans: True and False
- 1.2 Boolean operators in C++.....................................................................................................
- 1.2.1 and: &&.................................................................................................................................
- 1.2.2 or: ||........................................................................................................................................
- 1.2.3 not: !......................................................................................................................................
- 1.3 Arithmetic operators in C++.................................................................................................
- 1.4 Equality operators in C++.....................................................................................................
- 1.5 Assignment operators in C++...............................................................................................
- 2 Operator Precedence.............................................................................................................
- 2.1 What is operator precedence?...............................................................................................
- 2.2 Operator precedence in C++.................................................................................................
- 1 Branching Statements (if, else, switch).................................................................................
- 1.1 The if statement
- 1.2 the switch statement
- 2 #include ..............................................................................................................
- 3 using namespace std;
- 4 int main(int argc, char *argv[])
- 5 {.............................................................................................................................................
- 6 switch( tolower( *argv[1] ) )................................................................................................
- 7 {............................................................................................................................................
- 8 // Error. Unreachable declaration.
- 9 char szChEntered[] = "Character entered was: ";.................................................................
- 10 case 'a' :
- 11 {
- 12 // Declaration of szChEntered OK. Local scope.
- 13 char szChEntered[] = "Character entered was: ";.................................................................
- 14 cout << szChEntered << "a\n"; } break; case 'b' :................................................................
- 15 // Value of szChEntered undefined.
- 16 cout << szChEntered << "b\n";.............................................................................................
- 17 break;
- 18 default:..................................................................................................................................
- 19 // Value of szChEntered undefined.......................................................................................
- 20 cout << szChEntered << "neither a nor b\n"; break;
- 21 }.............................................................................................................................................
- 22 }............................................................................................................................................
- 1 Control Structures.................................................................................................................
- 1.1 Conditional structure: if and else..........................................................................................
- 2 Loops (for, while, do)............................................................................................................
- 2.1 Iteration structures (loops)....................................................................................................
- 2.1.1 The while loop......................................................................................................................
- 2.1.2 The do-while loop.................................................................................................................
- 2.1.3 The for loop...........................................................................................................................
- 2.2 Jump statements....................................................................................................................
- 2.2.1 The break statement..............................................................................................................
- 2.2.2 The continue statement.........................................................................................................
- 2.2.3 The goto statement................................................................................................................
- 2.2.4 The exit function...................................................................................................................
- 2.3 The selective structure: switch..............................................................................................
- 2.4 The for statement
- 2.5 The while statement
- 4 Functions
- 5 Introduction to User-defined functions in C++
- 6 Functions with no parameters
- 6.1 Scope of variables.................................................................................................................
- 1 Functions with no type. The use of void...............................................................................
- 1 Functions with parameters and no return value
- 2 Functions that return values
- 2.1 Arguments passed by value and by reference.......................................................................
- 2.2 Default values in parameters.................................................................................................
- 3 Example function: sum of squares of integers
- 4 Example Function: Raising to the power
- 5 Call-by-value parameters
- 6 Further User-defined functions in C++
- 7 Call-by-reference parameters
- 7.1 Recursivity.............................................................................................................................
- 7.2 Declaring functions...............................................................................................................
- 8 Review Questions
- 9 Exercises
- 9.2 Overloaded functions............................................................................................................
- 9.3 inline functions......................................................................................................................
- 9.4 C++ Virtual Function - Properties:........................................................................................
- 9.5 C++ Virtual Function - Reasons:...........................................................................................
- 9.6 C++ Virtual function - Example:..........................................................................................
- 9.7 C++ Virtual function - Call Mechanism:..............................................................................
- 10 Arrays....................................................................................................................................
- 10.1 Initializing arrays..................................................................................................................
- 10.2 Accessing the values of an array...........................................................................................
- 10.3 Multidimensional arrays.......................................................................................................
- 10.4 Arrays as parameters.............................................................................................................
- 10.5 Initialization of null-terminated character sequences...........................................................
- 10.6 Using null-terminated sequences of characters.....................................................................
- 11 Input/Output with files..........................................................................................................
- 11.1 Open a file.............................................................................................................................
- 11.2 Closing a file.........................................................................................................................
- 11.3 Checking state flags..............................................................................................................
- 11.4 get and put stream pointers...................................................................................................
- 11.4.1 tellg() and tellp()...................................................................................................................
- 11.4.2 seekg() and seekp()...............................................................................................................
- 11.6 Random access files..............................................................................................................
- ifstream. The pararmeters of read() and write() are the data or variable and its length.................... 11.8 We use two new functions which are write(), a member of ofstream and read(), a member of the
- 11.9 write ( memory_block, size );read ( memory_block, size );.................................................
- 11.11 // Files.cpp : Defines the entry point for the console application.........................................
- 11.12 //.............................................................................................................................................
- 11.13 #include "stdafx.h"................................................................................................................
- 11.14 #include "fstream.h"..............................................................................................................
- 11.15 #include "iostream.h"............................................................................................................
- 11.16 ofstream dout;.......................................................................................................................
- 11.18 int main()...............................................................................................................................
- 11.19 {.............................................................................................................................................
- 11.20 dout.open("stud.txt", ios::out);..................................................................................
- 11.21 char text[5];...............................................................................................................
- 11.22 cout<<"Enter text"<<endl;........................................................................................
- 11.23 cin>>text;..................................................................................................................
- 11.24 dout.write(text,sizeof(text));.....................................................................................
- 11.25 dout.close();...............................................................................................................
- 11.26 return 0;.....................................................................................................................
- 11.27 }.............................................................................................................................................
- 11.29 Binary files............................................................................................................................
- 11.30 Buffers and Synchronization.................................................................................................
- 11.31 Header files...........................................................................................................................
- 11.32 Getting a stream....................................................................................................................
- 11.33 Passing streams to functions.................................................................................................
- 11.34 Item by item input and output...............................................................................................
- 11.35 Buffering and flush...............................................................................................................
- 11.36 Other input operations...........................................................................................................
- 11.37 Other output operations.........................................................................................................
- 11.38 Repositioning and error states...............................................................................................
- 12 Pointers..................................................................................................................................
- 12.1 What is a Pointer?.................................................................................................................
- 13 Pointers Simplified................................................................................................................
- 13.1 What You'll Learn.................................................................................................................
- 13.2 Inside Memory......................................................................................................................
- 13.3 Pointer Variables...................................................................................................................
- 13.4 The Marriage of Arrays and Pointers....................................................................................
- 13.5 Pointers to Characters...........................................................................................................
- 13.6 Arrays of Pointers.................................................................................................................
- 13.7 Pointers and C++ Type Safety...............................................................................................
- 13.8 Reference operator (&).........................................................................................................
- 13.9 Dereference operator (*).......................................................................................................
- 13.10 Declaring variables of pointer types.....................................................................................
- 13.11 Pointers and arrays................................................................................................................
- 13.12 Pointer initialization..............................................................................................................
- 13.13 Pointer arithmetics................................................................................................................
- 13.14 Pointers to pointers................................................................................................................
- 13.15 void pointers..........................................................................................................................
- 13.16 Null pointer...........................................................................................................................
- 13.17 Pointers to functions..............................................................................................................
- 13.18 Operators new and new[]......................................................................................................
- 13.19 Operator delete and delete[]..................................................................................................
- 14 Structures...............................................................................................................................
- 15 Structure with struct..............................................................................................................
- 15.1 What You'll Learn.................................................................................................................
- 15.2 Grouping in a Structure.........................................................................................................
- 15.2.1 The struct Statement..............................................................................................................
- 15.3 Initializing Structure Variables..............................................................................................
- 15.4 Structure Assignment............................................................................................................
- 16 Constructors..........................................................................................................................
- 17 Destructors............................................................................................................................
- 18 Classes...................................................................................................................................
- 18.1 C++ Tutorial - Class Data Members:....................................................................................
- 18.2 C++ Tutorial - Function members in classes:.......................................................................
- 18.2.1 Ordinary member functions :................................................................................................
- 18.2.2 Constructors:.........................................................................................................................
- 18.2.3 Destructors:...........................................................................................................................
- 18.3 C++ Tutorial - Access Level:................................................................................................
- 18.3.1 Private:..................................................................................................................................
- 18.3.2 Protected:..............................................................................................................................
- 18.3.3 Public:...................................................................................................................................
- 18.4 C++ Tutorial - Example of a class:.......................................................................................
- 18.5 Using a Class (Instantiation).................................................................................................
- 18.5.1 Instantiating an object...........................................................................................................
- 18.5.2 Using an object's member functions.....................................................................................
- 20 Fundamental Math Operators................................................................................................
- 20.1 What You'll Learn About.......................................................................................................
- 20.2 Reviewing the Basics............................................................................................................
- 20.2.1 The Unary Operators.............................................................................................................
- 20.2.2 Two Divisions and Remainder..............................................................................................
- 20.3 Order of Operators................................................................................................................
- 20.4 Advanced Assignments.........................................................................................................
- 20.4.1 Multiple Assignments...........................................................................................................
- 20.4.2 Compound Operators............................................................................................................
- 22 Special Operations................................................................................................................
- 22.1 What You'll Learn About.......................................................................................................
- 22.2 Combining Data Types..........................................................................................................
- 22.2.
- 22.2.2 Automatic Promotion............................................................................................................
- 22.2.3 The Typecast Operator..........................................................................................................
- 22.4 The sizeof Operator...............................................................................................................
- 22.6 Using the Conditional Operator............................................................................................
- 22.7 Adding and Subtracting One.................................................................................................
The first program uses the concept of standard output, which means “a general-purpose place to send output.” You will see other examples using standard output in different ways, but here it will just go to the console. The iostream package automatically defines a variable (an object) called cout that accepts all data bound for standard output. To send data to standard output, you use the operator <<. C programmers know this operator as the “bitwise left shift,” which will be described in the next chapter. Suffice it to say that a bitwise left shift has nothing to do with output. However, C++ allows operators to be overloaded. When you overload an operator, you give it a new meaning when that operator is used with an object of a particular type. With iostream objects, the operator << means “send to.” For example: cout << "howdy!"; sends the string “howdy!” to the object called cout (which is short for “console output”). That’s enough operator overloading to get you started. Chapter XX covers operator overloading in detail.
Namespaces
As mentioned in the previous chapter, one of the problems encountered in the C language is that you “run out of names” for functions and identifiers when your programs reach a certain size. Of course, you don’t really run out of names – however, it becomes harder to think of new ones after awhile. More importantly, when a program reaches a certain size it’s typically broken up into pieces, each of which is built and maintained by a different person or group. Since C effectively has a single arena where all the identifier and function names live, this means that all the developers must be careful not to accidentally use the same names in situations where they can conflict. This rapidly becomes tedious, time-wasting and, ultimately, expensive. Standard C++ has a mechanism to prevent this collison: the namespace keyword. Each set of C++ definitions in a library or program is “wrapped” in a namespace, and if some other definition has an identical name, but is in a different namespace, then there is no collision. Namespaces are a convenient and helpful tool, but their presence means you must be aware of them before you can write any programs at all. If you simply include a header file and use some functions or objects from that header, you’ll probably get strange-sounding errors when you try to compile the program, to the effect that the compiler cannot find any of the declarations for the items that you just included in the header file! After you see this message a few times you’ll become familiar with its meaning (which is: “you included the header file but all the declarations are within a namespace and you didn’t tell the compiler that you wanted to use the declarations in that namespace”). There’s a keyword that allows you to say “I want to use the declarations and/or definitions in this namespace.” This keyword, appropriately enough, is using. All of the Standard C++ libraries are wrapped in a single namespace, which is std (for “standard”). As this book uses the standard libraries almost exclusively, you’ll see the following using directive in almost every program: using namespace std; This means that you want to expose all the elements from the namespace called std. After this statement, you don’t have to worry that your particular library component is inside a namespace, since the using directive makes that namespace available throughout the file where the using directive was written. Exposing all the elements from a namespace after someone has gone to the trouble to hide them may seem a bit counterproductive, and in fact you should be careful about thoughtlessly doing this (as you’ll learn later in the book). However, the using directive only exposes those names for the current file, so it is not quite so drastic as it first sounds (but think twice about doing it in a header file – that is reckless). There’s a relationship between namespaces and the way header files are included. Before the current header file inclusion style of (that is, no trailing ‘ .h ’) was standardized, the typical way to include a header file was with the ‘ .h ’, such as <iostream.h>. At that time, namespaces were not part of the language, either. So to provide backwards compatibility with existing code, if you say #include <iostream.h> It means #include using namespace std;
However, in this book the standard include format will be used (without the ‘ .h ’) and so the using directive must be explicit. For now, that’s all you need to know about namespaces, but in Chapter XX the subject is covered much more thoroughly.
Fundamentals of program structure
A C or C++ program is a collection of variables, function definitions and function calls. When the program starts, it executes initialization code and calls a special function, “ main( ) .” You put the primary code for the program here. As mentioned earlier, a function definition consists of a return type (which must be specified in C++), a function name, an argument list in parentheses, and the function code contained in braces. Here is a sample function definition: int function() { // Function code here (this is a comment) } The above function has an empty argument list, and a body that contains only a comment. There can be many sets of braces within a function definition, but there must always be at least one set surrounding the function body. Since main( ) is a function, it must follow these rules. In C++, main( ) always has return type of int. C and C++ are free form languages. With few exceptions, the compiler ignores newlines and white space, so it must have some way to determine the end of a statement. Statements are delimited by semicolons. C comments start with /* and end with */. They can include newlines. C++ uses C-style comments and has an additional type of comment: //. The // starts a comment that terminates with a newline. It is more convenient than / / for one-line comments, and is used extensively in this book.
"Hello, world!"
And now, finally, the first program: //: C02:Hello.cpp // Saying Hello with C++ #include // Stream declarations using namespace std; int main() { cout << "Hello, World! I am " << 8 << " Today!" << endl; } ///:~ The cout object is handed a series of arguments via the ‘ << ’ operators. It prints out these arguments in left-to-right order. The special iostream function endl outputs the line and a newline. With iostreams, you can string together a series of arguments like this, which makes the class easy to use. In C, text inside double quotes is traditionally called a “string.” However, the Standard C++ library has a powerful class called string for manipulating text, and so I shall use the more precise term character array for text inside double quotes. The compiler creates storage for character arrays and stores the ASCII equivalent for each character in this storage. The compiler automatically terminates this array of characters with an extra piece of storage containing the value 0, to indicate the end of the character array. Inside a character array, you can insert special characters by using escape sequences. These consist of a backslash ( ** ) followed by a special code. For example \n means newline. Your compiler manual or local C guide gives a complete set of escape sequences; others include \t (tab), \ (backslash) and \b (backspace). Notice that the entire statement terminates with a semicolon. Character array arguments and constant numbers are mixed together in the above cout statement. Because the operator << is overloaded with a variety of meanings when used with cout , you can send cout a variety of different arguments, and it will “figure out what to do with the message.” Throughout this book you’ll notice that the first line of each file will be a comment that starts with the characters that start a comment (typically // ), followed by a colon. // my first program in C++
return 0; The return statement causes the main function to finish. return may be followed by a return code (in our example is followed by the return code 0). A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. This is the most usual way to end a C++ program.
You may have noticed that not all the lines of this program perform actions when the code is executed. There were lines containing only comments (those beginning by //). There were lines with directives for the compiler's preprocessor (those beginning by #). Then there were lines that began the declaration of a function (in this case, the main function) and, finally lines with statements (like the insertion into cout), which were all included within the block delimited by the braces ({}) of the main function.
Preprocessor directives (those that begin by #) are out of this general rule since they are not statements. They are lines read and discarded by the preprocessor and do not produce any code by themselves. Preprocessor directives must be specified in their own line and do not have to end with a semicolon (;).
Comments
Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code.
C++ supports two ways to insert comments:
// line comment / block comment /
The first of them, known as line comment, discards everything from where the pair of slash signs (//) is found up to the end of that same line. The second one, known as block comment, discards everything between the /* characters and the first appearance of the / characters, with the possibility of including more than one line. If you include comments within the source code of your programs without using the comment characters combinations //, / or */, the compiler will take them as if they were C++ expressions, most likely causing one or several error messages when you compile it.
Variables. Data Types.
Each variable needs an identifier that distinguishes it from the others, for example, in the previous code the variable identifiers were a, b and result, but we could have called the variables any names we wanted to invent, as long as they were valid identifiers.
Identifiers
A valid identifier is a sequence of one or more letters, digits or underline characters (). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and underline characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character ( ), but this is usually reserved for compiler specific keywords or external identifiers. In no case they can begin with a digit.
Another rule that you have to consider when inventing your own identifiers is that they cannot match any keyword of the C++ language or your compiler's specific ones since they could be confused with these. The standard reserved keywords are:
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while
Additionally, alternative representations for some operators cannot be used as identifiers since they are reserved words under some circumstances:
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Your compiler may also include some additional specific reserved keywords.
Very important: The C++ language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers.
Fundamental data types
When programming, we store the variables in our computer's memory, but the computer has to know what we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C++. A byte can store a relatively small amount of data: one single character or a small integer (generally an integer between 0 and 255). In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers.
Next you have a summary of the basic fundamental data types in C++, as well as the range of values that can be represented with each one:
Name Description Size Range char** Character or small integer. 1byte signed: -128 to 127 unsigned: 0 to 255 short int (short)
Short Integer. 2bytes signed: -32768 to 32767 unsigned: 0 to 65535 int Integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 long int (long)
Long integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 bool Boolean value. It can take one of two values: true or false.
1byte true or false
float Floating point number. 4bytes 3.4e +/- 38 (7 digits) double Double precision floating point number. 8bytes 1.7e +/- 308 (15 digits) long double Long double precision floating point number. 8bytes 1.7e +/- 308 (15 digits) wchar_t Wide character. 2bytes 1 wide character
- The values of the columns Size and Range depend on the architecture of the system where the program is compiled and executed. The values shown above are those found on most 32bit systems. But for other systems, the general specification is that int has the natural size suggested by the system architecture (one word ) and the four integer types char, short, int and long must each one be at least as large as the one preceding it. The same applies to the floating point types float, double and long double, where each one must provide at least as much precision as the preceding one.
Introducing strings
While a character array can be fairly useful, it is quite limited. It’s simply a group of characters in memory, but if you want to do anything with it you must manage all the little details. For example, the size of a quoted character array is fixed at compile time. If you have a character array and you want to add some more characters to it, you’ll need to understand quite a lot (inluding dynamic memory management, character array copying and concatenation) before you can get your wish. This is exactly the kind of thing we’d like to have an object do for us. The Standard C++ string class is designed to take care of (and hide) all the low-level manipulations of character arrays that were previously required of the C++ programmer. These manipulations have been
A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.
Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa.
Initialization of variables
When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by the value to which the variable will be initialized:
type identifier = initial_value ;
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write:
int a = 0;
The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()):
type identifier (initial_value) ;
For example:
int a (0);
Both ways of initializing variables are valid and equivalent in C++.
// initialization of variables #include using namespace std; int main () { int a=5; // initial value = 5 int b(2); // initial value = 2 int result; // initial value undetermined a = a + 3; result = a - b; cout << result; return 0; } 6
Specifying storage allocation
When creating a variable, you have a number of options to specify the lifetime of the variable, how the storage is allocated for that variable, and how the variable is treated by the compiler.
Global variables
Global variables are defined outside all function bodies and are available to all parts of the program (even code in other files). Global variables are unaffected by scopes and are always available (i.e., the lifetime of a global variable lasts until the program ends). If the existence of a global variable in one file
is declared using the extern keyword in another file, the data is available for use by the second file. Here’s an example of the use of global variables: //: C03:Global.cpp //{L} Global // Demonstration of global variables #include using namespace std; int globe; void func(); int main() { globe = 12; cout << globe << endl; func(); // Modifies globe cout << globe << endl; } ///:~ Here’s a file that accesses globe as an extern: //: C03:Global2.cpp {O} // Accessing external global variables extern int globe; // (The linker resolves the reference) void func() { globe = 47; } ///:~ Storage for the variable globe is created by the definition in Global.cpp , and that same variable is accessed by the code in Global2.cpp. Since the code in Global2.cpp is compiled separately from the code in Global.cpp , the compiler must be informed that the variable exists elsewhere by the declaration extern int globe; When you run the program, you’ll see that the call to func( ) does indeed affect the single global instance of globe. In Global.cpp , you can see the special comment tag (which is my own design): //{L} Global This says that to create the final program, the object file with the name Global2 must be linked in (there is no extension because the extension names of object files differ from one system to the next). In Global2.cpp , the first line has another special comment tag {O} which says “don’t try to create an executable out of this file, it’s being compiled so that it can be linked into some other executable.” The ExtractCode.cpp program at the end of this book reads these tags and creates the appropriate makefile so everything compiles properly (you’ll learn about makefile s at the end of this chapter).
Local variables
Local variables occur within a scope; they are “local” to a function. They are often called automatic variables because they automatically come into being when the scope is entered, and automatically go away when the scope closes. The keyword auto makes this explicit, but local variables default to auto so it is never necessary to declare something as an auto.
Register variables
A register variable is a type of local variable. The register keyword tells the compiler “make accesses to this variable as fast as possible.” Increasing the access speed is implementation dependent but, as the name suggests, it is often done by placing the variable in a register. There is no guarantee that the variable will be placed in a register or even that the access speed will increase. It is a hint to the compiler. There are restrictions to the use of register variables. You cannot take or compute the address of a register variable. A register variable can only be declared within a block (you cannot have global or static register variables). You can, however, use a register variable as a formal argument in a function (i.e., in the argument list).
This variable or function may be defined in another file or further down in the current file. As an example of the latter: //: C03:Forward.cpp // Forward function & data declarations #include using namespace std; // This is not actually external, but the // compiler must be told it exists somewhere: extern int i; extern void func(); int main() { i = 0; func(); } int i; // The data definition void func() { i++; cout << i; } ///:~ When the compiler encounters the declaration ‘ extern int i ’ it knows that the definition for i must exist somewhere as a global variable. When the compiler reaches the definition of i , no other declaration is visible so it knows it has found the same i declared earlier in the file. If you were to define i as static , you would be telling the compiler that i is defined globally (via the extern ), but it also has file scope (via the static ), so the compiler will generate an error.
Linkage
To understand the behavior of C and C++ programs, you need to know about linkage. In an executing program, an identifier is represented by storage in memory that holds a variable or a compiled function body. Linkage describes this storage it is seen by the linker. There are two types of linkage: internal linkage and external linkage. Internal linkage means that storage is created to represent the identifier only for the file being compiled. Other files may use the same identifier name with internal linkage, or for a global variable, and no conflicts will be found by the linker – separate storage is created for each identifier. Internal linkage is specified by the keyword static in C and C++. External linkage means that a single piece of storage is created to represent the identifier for all files being compiled. The storage is created once, and the linker must resolve all other references to that storage. Global variables and function names have external linkage. These are accessed from other files by declaring them with the keyword extern. Variables defined outside all functions (with the exception of const in C++) and function definitions default to external linkage. You can specifically force them to have internal linkage using the static keyword. You can explicitly state that an identifier has external linkage by defining it with the extern keyword. Defining a variable or function with extern is not necessary in C, but it is sometimes necessary for const in C++. Automatic (local) variables exist only temporarily, on the stack, while a function is being called. The linker doesn’t know about automatic variables, and they have no linkage.
Constants
In old (pre-Standard) C, if you wanted to make a constant, you had to use the preprocessor: #define PI 3. Everywhere you used PI , the value 3.14159 was substituted by the preprocessor (you can still use this method in C and C++). When you use the preprocessor to create constants, you place control of those constants outside the scope of the compiler. No type checking is performed on the name PI and you can’t take the address of PI (so you can’t pass a pointer or a reference to PI ). PI cannot be a variable of a user-defined type. The meaning of PI lasts from the point it is defined to the end of the file; the preprocessor doesn’t recognize scoping.
C++ introduces the concept of a named constant that is just like a variable, except its value cannot be changed. The modifier const tells the compiler that a name represents a constant. Any data type, built-in or user-defined, may be defined as const. If you define something as const and then attempt to modify it, the compiler will generate an error. You must specify the type of a const , like this: const int x = 10; In Standard C and C++, you can use a named constant in an argument list, even if the argument it fills is a pointer or a reference (i.e., you can take the address of a const ). A const has a scope, just like a regular variable, so you can “hide” a const inside a function and be sure that the name will not affect the rest of the program.
The const was taken from C++ and incorporated into Standard C, albeit quite differently. In C, the compiler treats a const just like a variable that has a special tag attached that says “don’t change me.” When you define a const in C, the compiler creates storage for it, so if you define more than one const with the same name in two different files (or put the definition in a header file), the linker will generate error messages about conflicts. The intended use of const in C is quite different from its intended use in C++ (in short, it’s nicer in C++).
Constant values
In C++, a const must always have an initialization value (in C, this is not true). Constant values for built-in types are expressed as decimal, octal, hexadecimal, or floating-point numbers (sadly, binary numbers were not considered important), or as characters. In the absence of any other clues, the compiler assumes a constant value is a decimal number. The numbers 47, 0 and 1101 are all treated as decimal numbers. A constant value with a leading 0 is treated as an octal number (base 8). Base 8 numbers can only contain digits 0-7; the compiler flags other digits as an error. A legitimate octal number is 017 (15 in base 10). A constant value with a leading 0x is treated as a hexadecimal number (base 16). Base 16 numbers contain the digits 0-9 and a-f or A-F. A legitimate hexadecimal number is 0x1fe (510 in base 10). Floating point numbers can contain decimal points and exponential powers (represented by e, which means “10 to the power”). Both the decimal point and the e are optional. If you assign a constant to a floating-point variable, the compiler will take the constant value and convert it to a floating-point number (this process is one form of what’s called implicit type conversion ). However, it is a good idea to use either a decimal point or an e to remind the reader you are using a floating-point number; some older compilers also need the hint. Legitimate floating-point constant values are: 1e4, 1.0001, 47.0, 0.0 and -1.159e-77. You can add suffixes to force the type of floating-point number: f or F forces a float , L or l forces a long double , otherwise the number will be a double. Character constants are characters surrounded by single quotes, as: ‘ A ’, ‘ 0 ’, ‘ ‘. Notice there is a big difference between the character ‘ 0 ’ (ASCII 96) and the value 0. Special characters are represented with the “backslash escape”: ‘ \n ’ (newline), ‘ \t ’ (tab), ‘ \ ’ (backslash), ‘ \r ’ (carriage return), ‘ " ’ (double quotes), ‘ ' ’ (single quote), etc. You can also express char constants in octal: ‘ \17 ’ or hexadecimal: ‘ \xff ’.
volatile
Whereas the qualifier const tells the compiler “this never changes” (which allows the compiler to perform extra optimizations) the qualifier volatile tells the compiler “you never know when this will change,” and prevents the compiler from performing any optimizations. Use this keyword when you read some value outside the control of your code, such as a register in a piece of communication hardware. A volatile variable is always read whenever its value is required, even if it was just read the line before. A special case of some storage being “outside the control of your code” is in a multithreaded program. If you’re watching a particular flag that is modified by another thread or process, that flag should be volatile so the compiler doesn’t make the assumption that it can optimize away multiple reads of the flag.
3.14159L // long double 6.02e23f // float
Any of the letters than can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings.
Character and string literals
There also exist non-numerical constants, like: 'z' 'p' "Hello world" "How do you do?"
The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes (").
When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions:
x 'x'
x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'.
Character and string literals have certain peculiarities, like the escape codes. These are special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (). Here you have a list of some of such escape codes:
\n newline \r carriage return \t tab \v vertical tab \b backspace \f form feed (page feed) \a alert (beep) ' single quote (') " double quote (") ? question mark (?) \ backslash ()
For example:
'\n' '\t' "Left \t Right" "one\ntwo\nthree"
Additionally, you can express any character by its numerical ASCII code by writing a backslash character () followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16) number. In the first case (octal) the digits must immediately follow the backslash (for example \23 or \40), in the second case (hexadecimal), an x character must be written before the digits themselves (for example \x20 or \x4A).
String literals can extend to more than a single line of code by putting a backslash sign () at the end of each unfinished line.
"string expressed in
two lines"
You can also concatenate several string constants separating them by one or several blank spaces, tabulators, newline or any other valid blank character:
"this forms" "a single" "string" "of characters"
Finally, if we want the string literal to be explicitly made of wide characters (wchar_t), instead of narrow characters (char), we can precede the constant with the L prefix:
L"This is a wide character string"
Wide characters are used mainly to represent non-English or exotic character sets.
Boolean literals
There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type bool by using the Boolean literals true and false.
Defined constants (#define)
You can define your own names for constants that you use very often without having to resort to memory-consuming variables, simply by using the #define preprocessor directive. Its format is:
#define identifier value
For example:
#define PI 3. #define NEWLINE '\n'
This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant, for example:
// defined constants: calculate circumference #include using namespace std; #define PI 3. #define NEWLINE '\n'; int main () { double r=5.0; // radius double circle;
circle = 2 * PI * r; cout << circle; cout << NEWLINE;
return 0; } 31.
In fact the only thing that the compiler preprocessor does when it encounters #define directives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to which they have been defined (3.14159265 and '\n' respectively).
The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the end, it will also be appended in all occurrences within the body of the program that the preprocessor replaces.
Declared constants (const)
With the const prefix you can declare constants with a specific type in the same way as you would do with a variable: