C++ Notes
C++ Notes
C++ Notes
C++ is a statically typed, compiled, general purpose, case-sensitive, free-form programming language that supports procedural, objectoriented, and generic programming. C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features. C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983. C++ is a superset of C, and that virtually any legal C program is a legal C++ program. Note: A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time.
Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of object-oriented development:
Standard Libraries
Standard C++ consists of three important parts:
The core language giving all the building blocks including variables, data types and literals etc. The C++ Standard Library giving a rich set of functions manipulating files, strings etc. The Standard Template Library (STL) giving a rich set of methods manipulating data structures etc.
Learning C++
The most important thing to do when learning C++ is to focus on concepts and not get lost in language technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones. C++ supports a variety of programming styles. You can write in the style of Fortran, C, Smalltalk, etc., in any language. Each style can achieve its aims effectively while maintaining runtime and space efficiency.
Use of C++
C++ is used by hundreds of thousands of programmers in essentially every application domain.
C++ is being highly used to write device drivers and other software that rely on direct manipulation of hardware under realtime constraints. C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts. Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interf aces of these systems are written in C++.
Text Editor:
This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi Name and version of text editor can vary on different operating systems. For exampe Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or Unix. The files you create with your editor are called source files, and for C++ they typically are named with the extension .cpp, .cp, or .c. Before starting your programming, make sure you have one text editor in place and you have enough experience to type your C++ program.
C++ Compiler:
This is actual C++ compiler which will be used to compile your source code into final executable program. Most C++ compilers don't care what extension you give your source code, but if you don't specify otherwise, many will use .cpp by default Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have respective Operating Systems.
Mac OS X Installation:
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Xcode is currently available at developer.apple.com/technologies/tools/.
Windows Installation:
To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage,www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW <version>.exe. While installing MinWG, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more. Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names. When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.
Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support. Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instant Variables - Each object has its unique set of instant variables. An object's state is created by the values assigned to these instant variables.
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed. The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++. The next line // main() is where program execution begins. is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line. The line int main() is the main function where program execution begins. The next line cout << "This is my first C++ program."; causes the message "This is my first C++ program" to be displayed on the screen. The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.
Open a text editor and add the code as above. Save the file as : hello.cpp Open a command prompt and go to the directory where you saved the file.
Type 'g++ hello.cpp ' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file. Now type ' a.out' to run your program. You will be able to see ' Hello World ' printed on the window. $ g++ hello.cpp $ ./a.out Hello World Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp. You can compile C/C++ programs using makefile. For more detail you can check Makefile Tutorial.
C++ Identifiers:
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9). C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in C++. Here are some examples of acceptable identifiers: mohd myname50 zara _temp abc j move_name a23b9 a_123 retVal
C++ Keywords:
The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.
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
Trigraphs:
A few characters have an alternative representation, called a trigraph sequence. A trigraph is a three-character sequence that represents a single character and the sequence always starts with two question marks. Trigraphs are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives. Following are most frequently used trigraph sequences: Trigraph ??= ??/ ??' ??( ??) ??! ??< ??> ??Replacement # \ ^ [ ] | { } ~
All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature.
Whitespace in C++:
A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it. Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the statement,
int age; There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the statement fruit = apples + oranges; // Get the total fruit
No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.
Comments in C++
Program comments are explanatory statements that you can include in the C++ code that you write and helps anyone reading it's source code. All programming languages allow for some form of comments. C++ supports single line and multi-line comments. All characters available inside any comment are ignored by C++ compiler. C++ comments start with /* and end with */. For example: /* This is a comment */ /* C++ comments can also * span multiple lines */ A comment can also start with //, extending to the end of the line. For example: #include <iostream> using namespace std; main() { cout << "Hello World"; // prints Hello World return 0; } When the above code is compiled, it will ignore // prints Hello World and final executable will produce following result: Hello World Within a /* and */ comment, // characters have no special meaning. Within a // comment, /* and */ have no special meaning. Thus, you can "nest" one kind of comment within the other kind. For example: /* Comment out printing of Hello World: cout << "Hello World"; // prints Hello World */
Several of the basic types can be modified using one or more of these type modifiers:
signed unsigned short long The following table shows the variable type, how much memory it takes to store the value memory, and what is maximum and minimum vaue which can be stored in such type of variables. Type char unsigned char signed char int unsigned int signed int short int unsigned short int signed short int long int signed long int unsigned long int float double long double wchar_t Typical Bit Width 1byte 1byte 1byte 4bytes 4bytes 4bytes 2bytes Range Range 4bytes 4bytes 4bytes 4bytes 8bytes 8bytes 2 or 4 bytes Typical Range -127 to 127 or 0 to 255 0 to 255 -127 to 127 -2147483648 to 2147483647 0 to 4294967295 -2147483648 to 2147483647 -32768 to 32767 0 to 65,535 -32768 to 32767 -2,147,483,647 to 2,147,483,647 same as long int 0 to 4,294,967,295 +/- 3.4e +/- 38 (~7 digits) +/- 1.7e +/- 308 (~15 digits) +/- 1.7e +/- 308 (~15 digits) 1 wide character
The sizes of variables might be different from those shown in the above table, depending on the compiler and the computer you are using.
Following is the example which will produce correct size of various data type on your cmputer. #include <iostream> using namespace std; int main() { cout << "Size cout << "Size cout << "Size cout << "Size cout << "Size cout << "Size cout << "Size return 0; }
of of of of of of of
char : " << sizeof(char) << endl; int : " << sizeof(int) << endl; short int : " << sizeof(short int) << endl; long int : " << sizeof(long int) << endl; float : " << sizeof(float) << endl; double : " << sizeof(double) << endl; wchar_t : " << sizeof(wchar_t) << endl;
This example uses endl which inserts a new-line character after every line and << operator is being used to pass multiple values out to the screen. We are also using sizeof() function to get size of various data types. When the above code is compiled and executed, it produces following result which can vary from machine to machine: Size Size Size Size Size Size Size of of of of of of of char : 1 int : 4 short int : 2 long int : 4 float : 4 double : 8 wchar_t : 4
typedef Declarations:
You can create a new name for an existing type using typedef. Following is the simple syntax to define a new type using typedef: typedef type newname; For example, the following tells the compiler that feet is another name for int: typedef int feet; Now, the following declaration is perfectly legal and creates an integer variable called distance: feet distance;
Enumerated Types:
An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the enumeration. To create an enumeration requires the use of the keyword enum. The general form of an enumeration type is: enum enum-name { list of names } var-list; Here, The enum-name is the enumeration's type name. The list of names is comma separated. For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is assigned the value "blue". enum color { red, green, blue } c; c = blue; By default, the value of the first name is 0, the second name has the value 1, the third has the value 2, and so on. But you can give a name a specific value by adding an initializer. For example, in the following enumeration, green will have the value 5. enum color { red, green=5, blue }; Here blue will have a value of 6 because each name will be one greater than the one that precedes it.
C++ also allows to define various other type of variables which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes. Following section will cover how to define, declare and use various type of variables.
A variable declaration with an initializer is always a definition. This means that storage is allocated for the variable and could be declared as follows: int i = 100;
An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists elsewhere in the program. A variable can be declared multiple times in a program, but it must be defined only once. Following is the declaration of a variable with extern keyword: extern int i;
Though you can declare a variable multiple times in your C++ program but it can be decalred only once in a file, a function or a block of code.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows: type variable_name = value; Some examples are: int d = 3, f = 5; byte z = 22; double pi = 3.14159; char x = 'x'; // // // // initializing d and f. initializes z. declares an approximation of pi. the variable x has the value 'x'.
For declarations without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined. It is a good programming practice to initialize variables properly otherwise, sometime program would produce unexpected result. Try following example which makes use of various types of variables: #include <iostream> using namespace std; int main () { // Variable declaration: int a, b; int c; float f; // actual initialization a = 10; b = 20; c = a + b; cout << c << endl ; f = 70.0/3.0; cout << f << endl ; return 0; } When the above code is compiled and executed, it produces following result: 30 23.3333
lvalue : An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue : An expression that is an rvalue may appear on the right- but not left-hand side of an assignment. Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement: int g = 20; But following is not a valid statement and would generate compile-time error: 10 = 20;
Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables. We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables.
Local Variables:
Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables: #include <iostream> using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; }
Global Variables:
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold thei r value throughout the lifetime of your program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables: #include <iostream> using namespace std; // Global variable declaration: int g; int main () { // Local variable declaration: int a, b; // actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; }
A program can have same name for local and global variables but value of local variable inside a function will take preference. For example: #include <iostream> using namespace std; // Global variable declaration: int g = 20; int main () { // Local variable declaration: int g = 10; cout << g; return 0; } When the above code is compiled and executed, it produces following result: 10
It is a good programming practice to initialize variables properly otherwise, sometime program would produce unexpected result.
C++ Constants/Literals
Constants refer to fixed values that the program may not alter and they are called literals. Constants can be of any of the basic data types and can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values. Again, constants are treated just like regular variables except that their values cannot be modified after their definition.
Integer literals:
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals: 212 215u 0xFeeL 078 032UU // // // // // Legal Legal Legal Illegal: 8 is not an octal digit Illegal: cannot repeat a suffix
Folowing are other examples of various type of Interger literals: 85 0213 0x4b 30 30u 30l 30ul // // // // // // // decimal octal hexadecimal int unsigned int long unsigned long
Floating-point literals:
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing using deciman form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples of floating-point literals: 3.14159 314159E-5L 510E 210f .e55 // // // // // Legal Legal Illegal: incomplete exponent Illegal: no decimal or exponent Illegal: missing integer or fraction
Boolean literals:
There are two Boolean literals and they are part of standard C++ keywords:
A value of true representing true. A value of false representing false. You should not consider the value of true equal to 1 and value of false equal to zero.
Character literals:
Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable . Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). There are certain characters in C++ when they are proceeded by a back slash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here you have a list of some of such escape sequence codes: Escape sequence \\ \' \" \? \a \b \f \n \r \t \v \ooo \xhh . . . Meaning \ character ' character " character ? character Alert or bell Backspace Form feed Newline Carriage return Horizontal tab Vertical tab Octal number of one to three digits Hexadecimal number of one or more digits
Following is the example to show few escape sequence characters: #include <iostream> using namespace std; int main() { cout << "Hello\tWorld\n\n"; return 0; } When the above code is compiled and executed, it produces following result: Hello World
String literals:
String literals are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long lines into multiple lines using string literals and separating them using whitespaces. Here are some examples of string literals. All the three forms are identical strings. "hello, dear" "hello, \ dear" "hello, " "d" "ear"
Defining Constants:
There are two simple ways in C++ to define constants:
signed unsigned long short The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition,signed and unsigned can be applied to char, and long can be applied to double. The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For exampleunsigned long int. C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without the int. The int is implied. For example, the following two statements both declare unsigned integer variables. unsigned x; unsigned int y; To understand the difference between the way that signed and unsigned integer modifiers are interpreted by C++, you should run the following short program: #include <iostream> using namespace std; /* This program shows the difference between * signed and unsigned integers. */ int main() { short int i; // a signed short integer short unsigned int j; // an unsigned short integer j = 50000; i = j; cout << i << " " << j; return 0; } When this program is run, following is the output: -15536 50000 The above result is because the bit pattern that represents 50,000 as a short unsigned integer is interpreted as -15,536 by a short.
restrict
A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Only C99 adds a new type qualifier called restrict.
static int count = 10; /* Global variable */ main() { while(count--) { func(); } return 0; } // Function definition void func( void ) { static int i = 5; // local static variable i++; std::cout << "i is " << i ; std::cout << " and count is " << count << std::endl; } When the above code is compiled and executed, it produces following result: i i i i i i i i i i is is is is is is is is is is 6 and count is 9 7 and count is 8 8 and count is 7 9 and count is 6 10 and count is 5 11 and count is 4 12 and count is 3 13 and count is 2 14 and count is 1 15 and count is 0
Here extern keyword is being used to declare count in another file. Now compile these two files as follows: $g++ main.cpp write.cpp -o write This will produce write executable program, try to execute write and check the result as follows: $./write 5
Operators in C++
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provides following type of operators:
Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators This chapter will examine the arithmetic, relational, and logical, bitwise, assignment and other operators one by one.
Arithmetic Operators:
There are following arithmetic operators supported by C++ language: Assume variable A holds 10 and variable B holds 20 then: Show Examples Operator Description + * / % ++ -Adds two operands Subtracts second operand from the first Multiply both operands Divide numerator by de-numerator Modulus Operator and remainder of after an integer division Increment operator, increases integer value by one Decrement operator, decreases integer value by one Example A + B will give 30 A - B will give -10 A * B will give 200 B / A will give 2 B % A will give 0 A++ will give 11 A-- will give 9
Relational Operators:
There are following relational operators supported by C++ language Assume variable A holds 10 and variable B holds 20 then:
Show Examples Operator Description == Checks if the value of two operands is equal or not, if yes then condition becomes true. Checks if the value of two operands is equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. Example (A == B) is not true.
!=
(A != B) is true.
>
<
(A < B) is true.
>=
<=
(A <= B) is true.
Logical Operators:
There are following logical operators supported by C++ language Assume variable A holds 1 and variable B holds 0 then: Show Examples Operator Description && Called Logical AND operator. If both the operands are non zero then condition becomes true. Example (A && B) is false.
||
Called Logical OR Operator. If any of the two operands is non zero then condition (A || B) is true. becomes true. Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
Bitwise Operators:
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows: p 0 0 1 1 q 0 1 1 0 p&q 0 0 1 0 p|q 0 1 1 1 p^q 0 1 0 1
Assume if A = 60; and B = 13; Now in binary format they will be as follows: A = 0011 1100 B = 0000 1101 -----------------
A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60 and variable B holds 13 then: Show Examples Operator Description & | ^ ~ Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand. Example (A & B) will give 12 which is 0000 1100 (A | B) will give 61 which is 0011 1101
Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is 0011 0001 in one operand but not both. Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. (~A ) will give -60 which is 1100 0011
<<
>>
Assignment Operators:
There are following assignment operators supported by C++ language: Show Examples Operator Description = Simple assignment operator, Assigns values from right side operands to left side operand Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Left shift AND assignment operator Right shift AND assignment operator Bitwise AND assignment operator Example C = A + B will assign value of A + B into C
+=
C += A is equivalent to C = C + A
-=
C -= A is equivalent to C = C - A
*=
C *= A is equivalent to C = C * A
/=
C /= A is equivalent to C = C / A
C %= A is equivalent to C = C % A C <<= 2 is same as C = C << 2 C >>= 2 is same as C = C >> 2 C &= 2 is same as C = C & 2
^= |=
bitwise exclusive OR and assignment operator bitwise inclusive OR and assignment operator
C ^= 2 is same as C = C ^ 2 C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by C++ Language. Operator sizeof Condition ? X : Y Description sizeof operator returns the size of a variable. For example sizeof(a), where a is integer, will return 4. Conditional operator. If Condition is true ? then it returns value X : otherwise value Y Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list. Member operators are used to reference individual members of classes, structures, and unions. Casting operators convert one data type to another. For example, int(2.2000) would return 2. Pointer operator & returns the address of an variable. For example &a; will give actual address of the variable. Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
C++ programming language provides following types of loop to handle looping requirements. Click the following links to check their detail. Loop Type while loop for loop do...while loop nested loops Description Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. Like a while statement, except that it tests the condition at the end of the loop body You can use one or more loop inside any another while, for or do..while loop.
Description Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.
C++ programming language provides following types of decision making statements. Click the following links to check their detail. Statement if statement if...else statement switch statement nested if statements nested switch statements Description An if statement consists of a boolean expression followed by one or more statements. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. A switch statement allows a variable to be tested for equality against a list of values. You can use one if or else if statement inside another if or else if statement(s). You can use one swicth statement inside another switch statement(s).
The ? : Operator:
We have covered conditional operator ? : in previous chapter which can be used to replace if...elsestatements. It has the following general form: Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
C++ Functions
A function is a group of statements that together perform a task. Every C++ program has at least one function which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions. A function is knows as with various names like a method or a sub-routine or a procedure etc.
Defining a Function:
The general form of a C++ function definition is as follows: return_type function_name( parameter list ) { body of the function } A C++ function definition consists of a function header and a function body. Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body: The function body contains a collection of statements that define what the function does.
Example:
Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two: // function returning the max between two numbers int max(int num1, int num2) { // local variable declaration int result; if (num1 > num2) result = num1; else result = num2; return result; }
Function Declarations:
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts: return_type function_name( parameter list ); For the above defined function max(), following is the function declaration: int max(int num1, int num2); Parameter names are not importan in function declaration only their type is required, so following is also valid declaration: int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function.
Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function. When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program. To call a function you simply need to pass the required parameters along with function name and if function returns a value then you can store returned value. For example: #include <iostream> using namespace std; // function declaration int max(int num1, int num2); int main () { // local variable declaration:
int a = 100; int b = 200; int ret; // calling a function to get max value. ret = max(a, b); cout << "Max value is : " << ret << endl; return 0; } // function returning the max between two numbers int max(int num1, int num2) { // local variable declaration int result; if (num1 > num2) result = num1; else result = num2; return result; } I kept max() function along with main() function and complied the source code. While running final executable, it would produce following result: Max value is : 200
Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways that arguments can be passed to a function: Call Type Call by value Description This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
Call by pointer
Call by reference
By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.
#include <iostream> using namespace std; int sum(int a, int b=20) { int result; result = a + b; return (result); } int main () { // local variable declaration: int a = 100; int b = 200; int result; // calling a function to add the values. result = sum(a, b); cout << "Total value is :" << result << endl; // calling a function again as follows. result = sum(a); cout << "Total value is :" << result << endl; return 0; } When the above code is compiled and executed, it produces following result: Total value is :300 Total value is :120
Numbers in C++
Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types.
// number printing; cout << "short s :" cout << "int i :" cout << "long l :" cout << "float f :" cout << "double d :" return 0; }
s i l f d
When the above code is compiled and executed, it produces following result: short int long float double s i l f d :10 :1000 :1000000 :230.47 :30949.4
7 8 9 10
Following a simple example to show few of the mathematical operations: #include <iostream> #include <cmath> using namespace std; int main () { // number definition: short s = 10;
i l f d
= = = =
// mathematical operations; cout << "sin(d) :" << sin(d) << endl; cout << "abs(i) :" << abs(i) << endl; cout << "floor(d) :" << floor(d) << endl; cout << "sqrt(f) :" << sqrt(f) << endl; cout << "pow( d, 2) :" << pow(d, 2) << endl; return 0; } When the above code is compiled and executed, it produces following result: sign(d) :-0.634939 abs(i) :1000 floor(d) :200 sqrt(f) :15.1812 pow( d, 2 ) :40149.7
C++ Arrays
C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Declaring Arrays:
To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows: type arrayName [ arraySize ]; This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement: double balance[10];
Initializing Arrays:
You can initialize C++ array elements either one by one or using a single statement as follows: double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array: If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}; You will create exactly the same array as you did in the previous example. balance[4] = 50.0; The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th ie. last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representaion of the same array we discussed above:
int main () { int n[ 10 ]; // n is an array of 10 integers // initialize elements of array n to 0 for ( int i = 0; i < 10; i++ ) { n[ i ] = i + 100; // set element at location i to i + 100 } cout << "Element" << setw( 13 ) << "Value" << endl; // output each array element's value for ( int j = 0; j < 10; j++ ) { cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; } return 0; } This program makes use setw() function to format the output. When the above code is compiled and executed, it produces following result: Element 0 1 2 3 4 5 6 7 8 9 Value 100 101 102 103 104 105 106 107 108 109
C++ Strings
C++ provides following two types of string representations:
The C-style character string. The string class type introduced with Standard C++.
The C-style character string originated within the C language and continues to be supported within C++. This string is actually a onedimensional array of characters which is terminated by a nullcharacter '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; If you follow the rule of array initialization then you can write the above statement as follows: char greeting[] = "Hello"; Following is the memory presentation of above defined string in C/C++:
Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above mentioned string: #include <iostream> using namespace std; int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; cout << "Greeting message: "; cout << greeting << endl; return 0; } When the above code is compiled and executed, it produces result something as follows: Greeting message: Hello C++ supports a wide range of functions that manipulate null-terminated strings: S.N. Function & Purpose 1 2 3 4 5 6 strcpy(s1, s2); Copies string s2 into string s1. strcat(s1, s2); Concatenates string s2 onto the end of string s1. strlen(s1); Returns the length of string s1. strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
Following example makes use of few of the above mentioned functions: #include <iostream> #include <cstring>
using namespace std; int main () { char str1[10] = "Hello"; char str2[10] = "World"; char str3[10]; int len ; // copy str1 into str3 strcpy( str3, str1); cout << "strcpy( str3, str1) : " << str3 << endl; // concatenates str1 and str2 strcat( str1, str2); cout << "strcat( str1, str2): " << str1 << endl; // total lenghth of str1 after concatenation len = strlen(str1); cout << "strlen(str1) : " << len << endl; return 0; } When the above code is compiled and executed, it produces result something as follows: strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10
C++ Pointers
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them. As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined: #include <iostream> using namespace std; int main () { int var1; char var2[10]; cout << "Address of var1 variable: "; cout << &var1 << endl; cout << "Address of var2 variable: "; cout << &var2 << endl; return 0; } When the above code is compiled and executed, it produces result something as follows: Address of var1 variable: 0xbfebd5c0 Address of var2 variable: 0xbfebd5b6
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
// actual variable declaration. // pointer variable // store address of var in pointer variable
cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0; } When the above code is compiled and executed, it produces result something as follows: Value of var variable: 20 Address stored in ip variable: 0xbfc601ac Value of *ip variable: 20
C++ References
A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.
You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. A reference must be initialized when it is created. Pointers can be initialized at any time.
Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer reference initialized to i" and read the second declaration as "s is a double reference initialized to d.". Following example makes use of references on int and double: #include <iostream> using namespace std; int main () { // declare simple variables int i; double d; // declare reference variables int& r = i; double& s = d; i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r d = 11.7; cout << "Value of d : " << d << endl; cout << "Value of d reference : " << s return 0; } When the above code is compiled together and executed, it produces following result: Value Value Value Value of of of of i i d d : 5 reference : 5 : 11.7 reference : 11.7
<< endl;
<< endl;
References are usually used for function argument lists and function return values. So following are two important subjects related to C++ references which should be clear to a C++ programmer: Concept References as parameters Reference as return value Description C++ supports passing references as function parameter more safely than parameters. You can return reference from a C++ function like a any other data type can be returned.
Following are the important functions which we use while working with date and time in C or C++. All these functions are part of standard C and C++ library and you can check their detail using reference to C++ standard library given below. SN Function & Purpose 1 time_t time(time_t *time); This returns the current calendar time of the system in number of seconds elapsed since January 1, 1970. If the system has no time, .1 is returned. char *ctime(const time_t *time); This returns a pointer to a string of the form day month year hours:minutes:seconds year\n\0. struct tm *localtime(const time_t *time); This returns a pointer to the tm structure representing local time. clock_t clock(void); This returns a value that approximates the amount of time the calling program has been running. A value of .1 is returned if the time is not available. char * asctime ( const struct tm * time ); This returns a pointer to a string that contains the information stored in the structure pointed to by time converted into the form: day month date hours:minutes:seconds year\n\0 struct tm *gmtime(const time_t *time); This returns a pointer to the time in the form of a tm structure. The time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich Mean Time (GMT). time_t mktime(struct tm *time); This returns the calendar-time equivalent of the time found in the structure pointed to by time. double difftime ( time_t time2, time_t time1 ); This function calculates the difference in seconds between time1 and time2. size_t strftime(); This function can be used to format date and time a specific format.
2 3
7 8 9
// current date/time based on current system time_t now = time(0); // convert now to string form char* dt = ctime(&now); cout << "The local date and time is: " << dt << endl; // convert now to tm struct for UTC tm *gmtm = gmtime(&now); dt = asctime(gmtm); cout << "The UTC date and time is:"<< dt << endl; } When the above code is compiled and executed, it produces following result: The local date and time is: Sat Jan The UTC date and time is:Sun Jan 8 20:07:41 2011
9 03:07:41 2011
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc, this is called output operation.
<iomanip> <fstream>
Please enter your name: cplusplus Your name is: cplusplus The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables. The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following: cin >> name >> age; This will be equivalent to the following two statements: cin >> name; cin >> age;
C/C++ arrays allow you to define variables that combine several data items of the same kind butstructure is another user defined data type which allows you to combine data items of different kinds. Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:
Defining a Structure:
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this: struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure: struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }book;
// book 1 specification strcpy( Book1.title, "Learn C++ Programming"); strcpy( Book1.author, "Chand Miyan"); strcpy( Book1.subject, "C++ Programming"); Book1.book_id = 6495407; // book 2 specification strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Yakit Singha"); strcpy( Book2.subject, "Telecom"); Book2.book_id = 6495700;
// Print Book1 info cout << "Book 1 title : " << Book1.title <<endl; cout << "Book 1 author : " << Book1.author <<endl; cout << "Book 1 subject : " << Book1.subject <<endl; cout << "Book 1 id : " << Book1.book_id <<endl; // Print Book2 info cout << "Book 2 title : " << Book2.title <<endl; cout << "Book 2 author : " << Book2.author <<endl; cout << "Book 2 subject : " << Book2.subject <<endl; cout << "Book 2 id : " << Book2.book_id <<endl; return 0; } When the above code is compiled and executed, it produces following result: Book Book Book Book Book Book Book Book 1 1 1 1 2 2 2 2 title : Learn C++ Programming author : Chand Miyan subject : C++ Programming id : 6495407 title : Telecom Billing author : Yakit Singha subject : Telecom id : 6495700
// book 1 specification strcpy( Book1.title, "Learn C++ Programming"); strcpy( Book1.author, "Chand Miyan"); strcpy( Book1.subject, "C++ Programming"); Book1.book_id = 6495407; // book 2 specification strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Yakit Singha"); strcpy( Book2.subject, "Telecom"); Book2.book_id = 6495700; // Print Book1 info printBook( Book1 ); // Print Book2 info printBook( Book2 ); return 0; }
void printBook( struct Books book ) { cout << "Book title : " << book.title <<endl; cout << "Book author : " << book.author <<endl; cout << "Book subject : " << book.subject <<endl; cout << "Book id : " << book.book_id <<endl; } When the above code is compiled and executed, it produces following result: Book Book Book Book Book Book Book Book title : Learn C++ Programming author : Chand Miyan subject : C++ Programming id : 6495407 title : Telecom Billing author : Yakit Singha subject : Telecom id : 6495700
Pointers to Structures:
You can define pointers to structures in very similar way as you define pointer to any other variable as follows: struct Books *struct_pointer; Now you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows: struct_pointer = &Book1; To access the members of a structure using a pointer to that structure, you must use the -> operator as follows: struct_pointer->title; Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept: #include <iostream> using namespace std; void printBook( struct Books *book ); struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main( ) { struct Books Book1; struct Books Book2;
// Book 1 specification strcpy( Book1.title, "Learn C++ Programming"); strcpy( Book1.author, "Chand Miyan"); strcpy( Book1.subject, "C++ Programming"); Book1.book_id = 6495407; // Book 2 specification strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Yakit Singha"); strcpy( Book2.subject, "Telecom"); Book2.book_id = 6495700;
// Print Book1 info, passing address of structure printBook( &Book1 ); // Print Book1 info, passing address of structure printBook( &Book2 ); return 0; } // This function accept pointer to structure as parameter. void printBook( struct Books *book ) { cout << "Book title : " << book->title <<endl; cout << "Book author : " << book->author <<endl; cout << "Book subject : " << book->subject <<endl; cout << "Book id : " << book->book_id <<endl; } When the above code is compiled and executed, it produces following result: Book Book Book Book Book Book Book Book title : Learn C++ Programming author : Chand Miyan subject : C++ Programming id : 6495407 title : Telecom Billing author : Yakit Singha subject : Telecom id : 6495700