C++ Character (char) Data Type ”; Previous Next The character (char) data type in C++ stands for alphanumeric values, which can be a wide range of characters. These may include alphabets like ”a”, ”b”, and ”c”, numeric values like ”1”, ”2”, and ”3”, symbols like ”#”, ”$”, and ”&”, and many more. The character data type takes 1 Byte (i.e., 8 bits) of memory space to store characters. In C++, the keyword “char” is used to declare a character variable. In this tutorial, we will explore more about character data type, and its corresponding variables. Use Character (char) Data Type The following are some of the uses of character (char) data type − The char data type is used when we need to hold only a single character and do not need the overhead of String. The char data type can also be used in primitive form as an array without the use of a string literal. In ASCII form, char data type can be used to represent numeric values and vice-versa. Values of char Data Type The character (char) data type in C++ can have multiple values, and these values are as follows − Uppercase Alphabets, like A, B, Z, etc. Lowercase Alphabets, like a, b, z, etc. Symbols, like $, %, &, etc. Escape Sequences, which will be discussed later in this article. Creating a Character (char) Variable We can declare a character variable using the “char” keyword followed by the variable name. Syntax Use the following syntax to create a char type variable − char variable_name = [value]; Here, [value] is an optional and can be used to assign value during the declaration. Example In the following example, we are declaring a char variable, assigning a value to it. // C++ program to demonstrate // Character data type #include <iostream> using namespace std; int main(){ char ch; return 0; } Example of Character (char) Data Type The following example shows the use of different character data types − // C++ program to demonstrate // Character data type #include <iostream> using namespace std; int main() { char ch,ch1,ch2; ch=”a”; //this is an alphabet ch1=”&”; //this is a symbol ch2=”1”; //this is a number cout<<ch<<endl<<ch1<<endl<<ch2<<endl; return 0; } Output a & 1 ASCII Values of Characters ASCII stands for the “American Standard Code for Information Interchange”. It was the first set of encoding values assigned to different characters and symbols. The character sets used in modern computers, in HTML, and on the Internet, are all based on ASCII. The ASCII table describes a numeric value for all character types, and these values can be used to declare a character without the explicit use of the character itself. It contains the numbers from 0-9, the upper and lower case English letters from A to Z, and some special characters. The following data gives a reference for all ASCII values of characters available in C++ − ASCII Range of ”a” to ”z” = 97-122 ASCII Range of ”A” to ”Z” = 65-90 ASCII Range of ”0” to ”9” = 48-57 Example to Show ASCII Declaration The following example shows how a user can declare a character variable using ASCII values, without explicit usage of the character itself − #include <iostream> using namespace std; int main() { char ch,ch1,ch2; ch=65; //this is an alphabet ch1=45; //this is a symbol ch2=55; //this is a number cout<<ch<<endl<<ch1<<endl<<ch2<<endl; return 0; } Output A - 7 Implicit Conversion of Character Variables Character variables can be implicitly converted to their integer values using ASCII references, and vice-versa. Hence, when we declare a character in C++, we can reference their ASCII value, whereas an ASCII numerical can be used to access its character value as well. This is done using implicit conversion or typecasting of data types. We can add a keyword of the data type we need to convert the given variable into, and the compiler changes the data type automatically. For example, if we write char(97), it will load the character value of ASCII number 97, which is ‘a’. This is also possible for converting the character data type to integral (ASCII) values. This is clearly explained in the examples given below − Example The following example shows the implicit typecasting of char to int, and vice-versa − #include <iostream> using namespace std; int main() { char c = ”$”; int a = 97; cout << “The Corresponding ASCII value of ”$” : “; cout << int(c) << endl; cout << “The Corresponding character value of 97 : “; cout << char(a) << endl; return 0; } Output The Corresponding ASCII value of ”$” : 36 The Corresponding character value of 97 : a ESCAPE SEQUENCE IN C++ Character variables which begin with a backslash (“”) are called escape sequences. These determine on the output sequence on the output window of a compiler. In this context, backslash is also called as the ‘Escape Character’. The following table shows different types of escape sequences available in C++ − S. No. Escape Sequences Character 1. n Newline 2. \ Backslash 3. t Horizontal Tab 4. v Vertical Tab 5. Null Character The usage of escape sequences is clearly explained in the following example code − Example 1 #include <iostream> using namespace std;
Category: cplusplus
C++ Arrays
C++ Arrays ”; Previous Next 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, i.e., 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 − Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − double salary = balance[9]; The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays − Live Demo #include <iostream> using namespace std; #include <iomanip> using std::setw; 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 of setw() function to format the output. When the above code is compiled and executed, it produces the following result − Element Value 0 100 1 101 2 102 3 103 4 104 5 105 6 106 7 107 8 108 9 109 Arrays in C++ Arrays are important to C++ and should need lots of more detail. There are following few important concepts, which should be clear to a C++ programmer − Sr.No Concept & Description 1 Multi-dimensional arrays C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. 2 Pointer to an array You can generate a pointer to the first element of an array by simply specifying the array name, without any index. 3 Passing arrays to functions You can pass to the function a pointer to an array by specifying the array”s name without an index. 4 Return array from functions C++ allows a function to return an array. Print Page Previous Next Advertisements ”;
C++ Pointers
C++ Pointers ”; Previous Next 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 − Live Demo #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 the following result − Address of var1 variable: 0xbfebd5c0 Address of var2 variable: 0xbfebd5b6 What are Pointers? A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is − type *var-name; Here, type is the pointer”s base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration − int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character 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. Using Pointers in C++ There are few important operations, which we will do with the pointers very frequently. (a) We define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations − Live Demo #include <iostream> using namespace std; int main () { int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // 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 Pointers in C++ Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer − Sr.No Concept & Description 1 Null Pointers C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries. 2 Pointer Arithmetic There are four arithmetic operators that can be used on pointers: ++, –, +, – 3 Pointers vs Arrays There is a close relationship between pointers and arrays. 4 Array of Pointers You can define arrays to hold a number of pointers. 5 Pointer to Pointer C++ allows you to have pointer on a pointer and so on. 6 Passing Pointers to Functions Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. 7 Return Pointer from Functions C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well. Print Page Previous Next Advertisements ”;
C++ Basic Syntax
C++ Basic Syntax ”; Previous Next When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other”s methods. Let us now briefly look into what a class, object, methods, and instant variables mean. 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/blueprint that describes 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. Instance Variables − Each object has its unique set of instance variables. An object”s state is created by the values assigned to these instance variables. C++ Program Structure Let us look at a simple code that would print the words Hello World. Live Demo #include <iostream> using namespace std; // main() is where program execution begins. int main() { cout << “Hello World”; // prints Hello World return 0; } Let us look at the various parts of the above program − 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 << “Hello World”; causes the message “Hello World” 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. Compile and Execute C++ Program Let”s look at how to save the file, compile and run the program. Please follow the steps given below − 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 details, you can check our ”Makefile Tutorial”. Semicolons and Blocks in C++ In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity. For example, following are three different statements − x = y; y = y + 1; add(x, y); A block is a set of logically connected statements that are surrounded by opening and closing braces. For example − { cout << “Hello World”; // prints Hello World return 0; } C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a statement in a line. For example − x = y; y = y + 1; add(x, y); is the same as x = y; y = y + 1; add(x, y); 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 zara abc move_name a_123 myname50 _temp j a23b9 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 else new this auto enum operator throw bool explicit private true break export protected try case extern public typedef catch false register typeid char float reinterpret_cast typename class for return union const friend short unsigned const_cast goto signed using continue if sizeof virtual default inline static void delete int static_cast volatile do long struct wchar_t double mutable switch while dynamic_cast namespace template 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. Statement 1 int age; In the above statement there must be at least one whitespace character
C++ Cheat Sheet
C++ – Cheat Sheet ”; Previous Next This C++ programing cheat sheet can be very handy to use and provides key information in a short time frame. It is tailormade for people who want to address important topics and leap into the world of programming in C++. This includes all major and minor details one might need to surf through, and contains examples and code snippets to guide people on how to practically use this language. Introduction to C++ Programming Language C++ stands out as a robust and efficient programming language. It”s a cornerstone for crafting operating systems, software for embedded systems, and the engines that power video games. Due to its demanding nature for learners, a cheat sheet can be an invaluable tool for both programmers new to the field and those with experience. Basics of C++ The First Program: Hello World The very foundation of any programming language is the process of it”s development. And any beginner starts to learn a programming language by learning it”s syntax. So, let”s start by writing the very first program in C++, ie. Hello World − Example #include <bits/stdc++.h> using namespace std; // main() is where program execution begins. int main() { cout<<“Hello World”<<endl; // This is where you write your code return 0; } Output Hello World Comments Comments in C++ are used to write extra information that are useful to the programmer. C supports single-line comment // is used to indicate the single-line comment, whereas /* is used to start a multi-line comment and */ to end it. Example #include <bits/stdc++.h> using namespace std; int main() { /* This is multi-lined comment. The below statement will only print Hello World*/ cout<<“Hello World”<<endl; // This is a single-lined comment return 0; } Output Hello World Input and Output Statements Here, “cin” is the input statement, accompanied by “>>”, whereas “cout” is the output statement, accompanied by “>>”. Example #include <bits/stdc++.h> using namespace std; int main() { //declaration of an integer variable int age; cout << “Enter your age: “<<endl; cin >> age; cout << “Your age is: ” << age << endl; return 0; } Variables Variables are areas of storage where different types of data can be invariably stored. The variables in c++ must be declared before using, and the names of variables must start with an alphabet, and can contain letters, numbers and underscore(_). Example #include <bits/stdc++.h> using namespace std; int main() { // Declaring multiple variables int a, b, c; char ch; string s; return 0; } Keywords in C++ Keywords are special type of words that are reserved by the compiler of a specific language and can’t be explicitly used by the programmer. Some of these keywords are as follows − asm else new this auto enum operator throw bool explicit private true break export protected try case extern public typedef catch false register typeid char float reinterpret_cast typename class for return union const friend short unsigned const_cast goto signed using continue if sizeof virtual default inline static void delete int static_cast volatile do long struct wchar_t double mutable switch while dynamic_cast namespace template Data Types Data types are types of available classifications of storage where variables are stored in the memory. Data types can be categorized into three sections − Primitive data types Primitive data types are already existing in the c++ language libraries. These can be used without any modification. Int The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647. Float Floating Point data type is used for storing single-precision floating-point values or decimal values. The keyword used for the floating-point data type is float. Float variables typically require 4 bytes of memory space. Char Character data type is used for storing characters. The keyword used for the character data type is char. Characters typically require 1 byte of memory space and range from -128 to 127 or 0 to 255. Double Double Floating Point data type is used for storing double-precision floating-point values or decimal values. The keyword used for the double floating-point data type is double. String String data type is used for storing multiple characters together in a single variable. Bool Boolean data type is used for storing Boolean or logical values. A Boolean variable can store either true or false. The keyword used for the Boolean data type is bool. Example int main() { int age=12; //takes only whole numbers, size is 4 Bytes float weight=70.4; //takes decimal valued numbers, size is 4 Bytes char alpha=”a”; //takes single characters as per ASCII, size is 1 Bytes string s=”hey siri”; //takes multiple characters, size is variable double d=2.2222; //takes more precise floating point numbers, size is 8 Bytes bool k=true; //takes only true or false values (or 0/1) return 0; } Derived data types These are derived from the primitive datatypes , and are referred to
C++ Comments
Comments in C++ ”; Previous Next Program comments are explanatory statements that you can include in the C++ code. These comments help anyone reading the 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 − Live Demo #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 the 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 */ Print Page Previous Next Advertisements ”;
C++ Files and Streams
C++ Files and Streams ”; Previous Next So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively. This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types − Sr.No Data Type & Description 1 ofstream This data type represents the output file stream and is used to create files and to write information to files. 2 ifstream This data type represents the input file stream and is used to read information from files. 3 fstream This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files. To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file. Opening a File A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects. void open(const char *filename, ios::openmode mode); Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened. Sr.No Mode Flag & Description 1 ios::app Append mode. All output to that file to be appended to the end. 2 ios::ate Open a file for output and move the read/write control to the end of the file. 3 ios::in Open a file for reading. 4 ios::out Open a file for writing. 5 ios::trunc If the file already exists, its contents will be truncated before opening the file. You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax − ofstream outfile; outfile.open(“file.dat”, ios::out | ios::trunc ); Similar way, you can open a file for reading and writing purpose as follows − fstream afile; afile.open(“file.dat”, ios::out | ios::in ); Closing a File When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination. Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects. void close(); Writing to a File While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object. Reading from a File You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object. Read and Write Example Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen − Live Demo #include <fstream> #include <iostream> using namespace std; int main () { char data[100]; // open a file in write mode. ofstream outfile; outfile.open(“afile.dat”); cout << “Writing to the file” << endl; cout << “Enter your name: “; cin.getline(data, 100); // write inputted data into the file. outfile << data << endl; cout << “Enter your age: “; cin >> data; cin.ignore(); // again write inputted data into the file. outfile << data << endl; // close the opened file. outfile.close(); // open a file in read mode. ifstream infile; infile.open(“afile.dat”); cout << “Reading from the file” << endl; infile >> data; // write the data at the screen. cout << data << endl; // again read the data from the file and display it. infile >> data; cout << data << endl; // close the opened file. infile.close(); return 0; } When the above code is compiled and executed, it produces the following sample input and output − $./a.out Writing to the file Enter your name: Zara Enter your age: 9 Reading from the file Zara 9 Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement. File Position Pointers Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (“seek get”) for istream and seekp (“seek put”) for ostream. The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream. The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file”s starting location. Some examples of positioning the “get” file-position pointer are − // position to the nth byte of fileObject (assumes ios::beg) fileObject.seekg( n ); // position n bytes forward in fileObject fileObject.seekg( n, ios::cur ); // position n bytes back from end of fileObject fileObject.seekg( n, ios::end ); // position at end of fileObject fileObject.seekg( 0, ios::end ); Print
C++ Exception Handling
C++ Exception Handling ”; Previous Next An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. try − A try block identifies a block of code for which particular exceptions will be activated. It”s followed by one or more catch blocks. Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows − try { // protected code } catch( ExceptionName e1 ) { // catch block } catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block } You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations. Throwing Exceptions Exceptions can be thrown anywhere within a code block using throw statement. The operand of the throw statement determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown. Following is an example of throwing an exception when dividing by zero condition occurs − double division(int a, int b) { if( b == 0 ) { throw “Division by zero condition!”; } return (a/b); } Catching Exceptions The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch. try { // protected code } catch( ExceptionName e ) { // code to handle ExceptionName exception } Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should handle any type of exception that is thrown in a try block, you must put an ellipsis, …, between the parentheses enclosing the exception declaration as follows − try { // protected code } catch(…) { // code to handle any exception } The following is an example, which throws a division by zero exception and we catch it in catch block. Live Demo #include <iostream> using namespace std; double division(int a, int b) { if( b == 0 ) { throw “Division by zero condition!”; } return (a/b); } int main () { int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; } catch (const char* msg) { cerr << msg << endl; } return 0; } Because we are raising an exception of type const char*, so while catching this exception, we have to use const char* in catch block. If we compile and run above code, this would produce the following result − Division by zero condition! C++ Standard Exceptions C++ provides a list of standard exceptions defined in <exception> which we can use in our programs. These are arranged in a parent-child class hierarchy shown below − Here is the small description of each exception mentioned in the above hierarchy − Sr.No Exception & Description 1 std::exception An exception and parent class of all the standard C++ exceptions. 2 std::bad_alloc This can be thrown by new. 3 std::bad_cast This can be thrown by dynamic_cast. 4 std::bad_exception This is useful device to handle unexpected exceptions in a C++ program. 5 std::bad_typeid This can be thrown by typeid. 6 std::logic_error An exception that theoretically can be detected by reading the code. 7 std::domain_error This is an exception thrown when a mathematically invalid domain is used. 8 std::invalid_argument This is thrown due to invalid arguments. 9 std::length_error This is thrown when a too big std::string is created. 10 std::out_of_range This can be thrown by the ”at” method, for example a std::vector and std::bitset<>::operator[](). 11 std::runtime_error An exception that theoretically cannot be detected by reading the code. 12 std::overflow_error This is thrown if a mathematical overflow occurs. 13 std::range_error This is occurred when you try to store a value which is out of range. 14 std::underflow_error This is thrown if a mathematical underflow occurs. Define New Exceptions You can define your own exceptions by inheriting and overriding exception class functionality. Following is the example, which shows how you can use std::exception class to implement your own exception in standard way − Live Demo #include <iostream> #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return “C++ Exception”; } }; int main() { try { throw MyException(); } catch(MyException& e) { std::cout << “MyException caught” << std::endl; std::cout << e.what() << std::endl; } catch(std::exception& e) { //Other errors } } This would produce the following result − MyException caught C++ Exception Here, what() is a public method provided by exception class and it has been overridden by all the child exception classes. This returns the cause of an exception. Print Page Previous Next Advertisements ”;
C++ Standard Library
C++ Standard Library ”; Previous Next The C++ Standard Library can be categorized into two parts − The Standard Function Library − This library consists of general-purpose,stand-alone functions that are not part of any class. The function library is inherited from C. The Object Oriented Class Library − This is a collection of classes and associated functions. Standard C++ Library incorporates all the Standard C libraries also, with small additions and changes to support type safety. The Standard Function Library The standard function library is divided into the following categories − I/O, String and character handling, Mathematical, Time, date, and localization, Dynamic allocation, Miscellaneous, Wide-character functions, The Object Oriented Class Library Standard C++ Object Oriented Library defines an extensive set of classes that provide support for a number of common activities, including I/O, strings, and numeric processing. This library includes the following − The Standard C++ I/O Classes The String Class The Numeric Classes The STL Container Classes The STL Algorithms The STL Function Objects The STL Iterators The STL Allocators The Localization library Exception Handling Classes Miscellaneous Support Library Print Page Previous Next Advertisements ”;
C++ Overview
C++ Overview ”; Previous Next C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, 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 − Encapsulation Data hiding Inheritance Polymorphism 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. The ANSI Standard The ANSI standard is an attempt to ensure that C++ is portable; that code you write for Microsoft”s compiler will compile without errors, using a compiler on a Mac, UNIX, a Windows box, or an Alpha. The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers support the ANSI standard. Learning C++ The most important thing while learning C++ is to focus on concepts. 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 interfaces of these systems are written in C++. Print Page Previous Next Advertisements ”;