Numbers in C++ ”; Previous Next 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. Defining Numbers in C++ You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++ − Live Demo #include <iostream> using namespace std; int main () { // number definition: short s; int i; long l; float f; double d; // number assignments; s = 10; i = 1000; l = 1000000; f = 230.47; d = 30949.374; // number printing; cout << “short s :” << s << endl; cout << “int i :” << i << endl; cout << “long l :” << l << endl; cout << “float f :” << f << endl; cout << “double d :” << d << endl; return 0; } When the above code is compiled and executed, it produces the following result − short s :10 int i :1000 long l :1000000 float f :230.47 double d :30949.4 Math Operations in C++ In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use. C++ has a rich set of mathematical operations, which can be performed on various numbers. Following table lists down some useful built-in mathematical functions available in C++. To utilize these functions you need to include the math header file <cmath>. Sr.No Function & Purpose 1 double cos(double); This function takes an angle (as a double) and returns the cosine. 2 double sin(double); This function takes an angle (as a double) and returns the sine. 3 double tan(double); This function takes an angle (as a double) and returns the tangent. 4 double log(double); This function takes a number and returns the natural log of that number. 5 double pow(double, double); The first is a number you wish to raise and the second is the power you wish to raise it t 6 double hypot(double, double); If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse. 7 double sqrt(double); You pass this function a number and it gives you the square root. 8 int abs(int); This function returns the absolute value of an integer that is passed to it. 9 double fabs(double); This function returns the absolute value of any decimal number passed to it. 10 double floor(double); Finds the integer which is less than or equal to the argument passed to it. Following is a simple example to show few of the mathematical operations − Live Demo #include <iostream> #include <cmath> using namespace std; int main () { // number definition: short s = 10; int i = -1000; long l = 100000; float f = 230.47; double d = 200.374; // 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 the following result − sign(d) :-0.634939 abs(i) :1000 floor(d) :200 sqrt(f) :15.1812 pow( d, 2 ) :40149.7 Random Numbers in C++ There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function. Following is a simple example to generate few random numbers. This example makes use of time() function to get the number of seconds on your system time, to randomly seed the rand() function − Live Demo #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main () { int i,j; // set the seed srand( (unsigned)time( NULL ) ); /* generate 10 random numbers. */ for( i = 0; i < 10; i++ ) { // generate actual random number j = rand(); cout <<” Random Number : ” << j << endl; } return 0; } When the above code is compiled and executed, it produces the following result − Random Number : 1748144778 Random Number : 630873888 Random Number : 2134540646 Random Number : 219404170 Random Number : 902129458 Random Number : 920445370 Random Number : 1319072661 Random Number : 257938873 Random Number : 1256201101 Random Number : 580322989 Print Page Previous Next Advertisements ”;
Category: cplusplus
C++ Interfaces
Interfaces in C++ (Abstract Classes) ”; Previous Next An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class. The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data. A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing “= 0” in its declaration as follows − class Box { public: // pure virtual function virtual double getVolume() = 0; private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error. Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error. Classes that can be used to instantiate objects are called concrete classes. Abstract Class Example Consider the following example where parent class provides an interface to the base class to implement a function called getArea() − Live Demo #include <iostream> using namespace std; // Base class class Shape { public: // pure virtual function providing interface framework. virtual int getArea() = 0; void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derived classes class Rectangle: public Shape { public: int getArea() { return (width * height); } }; class Triangle: public Shape { public: int getArea() { return (width * height)/2; } }; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << “Total Rectangle area: ” << Rect.getArea() << endl; Tri.setWidth(5); Tri.setHeight(7); // Print the area of the object. cout << “Total Triangle area: ” << Tri.getArea() << endl; return 0; } When the above code is compiled and executed, it produces the following result − Total Rectangle area: 35 Total Triangle area: 17 You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape. Designing Strategy An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that operate similarly. The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application. This architecture also allows new applications to be added to a system easily, even after the system has been defined. Print Page Previous Next Advertisements ”;
C++ Overloading
C++ Overloading (Operator and Function) ”; Previous Next C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively. An overloaded declaration is a declaration that is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation). When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution. Function Overloading in C++ You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. Following is the example where same function print() is being used to print different data types − Live Demo #include <iostream> using namespace std; class printData { public: void print(int i) { cout << “Printing int: ” << i << endl; } void print(double f) { cout << “Printing float: ” << f << endl; } void print(char* c) { cout << “Printing character: ” << c << endl; } }; int main(void) { printData pd; // Call print to print integer pd.print(5); // Call print to print float pd.print(500.263); // Call print to print character pd.print(“Hello C++”); return 0; } When the above code is compiled and executed, it produces the following result − Printing int: 5 Printing float: 500.263 Printing character: Hello C++ Operators Overloading in C++ You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names: the keyword “operator” followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list. Box operator+(const Box&); declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows − Box operator+(const Box&, const Box&); Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below − Live Demo #include <iostream> using namespace std; class Box { public: double getVolume(void) { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } // Overload + operator to add two Box objects. Box operator+(const Box& b) { Box box; box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Main function for the program int main() { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); cout << “Volume of Box1 : ” << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << “Volume of Box2 : ” << volume <<endl; // Add two object as follows: Box3 = Box1 + Box2; // volume of box 3 volume = Box3.getVolume(); cout << “Volume of Box3 : ” << volume <<endl; return 0; } When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400 Overloadable/Non-overloadableOperators Following is the list of operators which can be overloaded − + – * / % ^ & | ~ ! , = < > <= >= ++ — << >> == != && || += -= /= %= ^= &= |= *= <<= >>= [] () -> ->* new new [] delete delete [] Following is the list of operators, which can not be overloaded − :: .* . ?: Operator Overloading Examples Here are various operator overloading examples to help you in understanding the concept. Sr.No Operators & Example 1 Unary Operators Overloading 2 Binary Operators Overloading 3 Relational Operators Overloading 4 Input/Output Operators Overloading 5 ++ and — Operators Overloading 6 Assignment Operators Overloading 7 Function call () Operator Overloading 8 Subscripting [] Operator Overloading 9 Class Member Access Operator -> Overloading Print Page Previous Next Advertisements ”;
C++ String Length
C++ String Length ”; Previous Next Length of a string is the number of characters present in the string. These characters can be of the data type char, and these include all alphanumeric elements, symbols and miscellaneous characters. In C++ programming language, there are two types of strings- Character Arrays of C-Style type, and String objects which are built-in objects of <string> class. The length of a string also includes white spaces, but in case a string includes a terminating character “”, the string ends at that character and the count of length is terminated just before that character. There are many ways to find the length of a given string. Some of these methods are iterative, whereas some also use in-built functions and methods. These methods are explained clearly in the following parts of this chapter − Using strlen() Method Using string::length() Method of String Class Using string::size() Method of String Class Using Iterative for Loop Using Iterative while Loop String Length Using strlen() Method Strings are defined as character arrays which are accessed using the pointer to the first iterator of the array. We can use strlen() method of C Library to calculate the length of C-type arrays. Syntax The following syntax shows how to use strlen() method to calculate the length of the string − strlen(string_name); Example The following example shows how to calculate the length of the string using strlen() method − #include <bits/stdc++.h> using namespace std; int main() { char s[]=”I love TP !!!”; cout<<“Length of string s : “<<strlen(s); return 0; } Output Length of string s : 13 String Length Using string::size() Method Most programmers commonly use string::size() method of string class when there is a need to calculate the length of a string in C++ programming language. It is the most basic method, and it is generally used while traversing a string object. Syntax The following syntax shows how to use size() method to calculate the length of the string − string_object.size(); Example The following example shows how to calculate the length of the string using size() method − #include <bits/stdc++.h> using namespace std; int main() { string s=”I love TP !!! and others”; cout<<“Length of string s : “<<s.size(); return 0; } Output Length of string s : 13 String Length Using string::length() Method We can also use length() method of string class to determine the length of the given string. Both length() and size() methods are part of <string> header file, and these are called as methods to the string object. Syntax The following syntax shows how to use length() method to calculate the length of the string − string_object.length(); Example The following example shows how to calculate the length of the string using length() method − #include <bits/stdc++.h> using namespace std; int main() { string s=”I love TP !!! and others”; cout<<“Length of string s : “<<s.length(); return 0; } Output Length of string s : 13 String Length Using while Loop We can use a simple while loop to iterate over the string and initialize a variable count to calculate the length of the string until we reach the end of the string. For each iteration, the count increases by one, hence the net result will be the length of the string. Syntax The following syntax shows how to use a while loop to calculate the length of the string − while(s[i]!=””) { [body] } Example The following example shows how to calculate the length of the string using a single while loop − #include <bits/stdc++.h> using namespace std; int main() { string s=”I love TP !!! and others”; int count=0, i=0; while(s[i]!=””) count++, i++; cout<<“Length of string s : “<<count; return 0; } Output Length of string s : 13 String Length Using a for Loop We can use a simple for loop to iterate over the string and initialize a variable count to calculate the length of the string until we reach the end of the string. For each iteration, the count increases by one, hence the net result will be the length of the string. Syntax The following syntax shows how to use a for loop to calculate the length of the string − for(int i=0;s[i]!=””;i++){ [body] } Example The following example shows how to calculate the length of the string using a single for loop − #include <bits/stdc++.h> using namespace std; int main() { string s=”I love TP !!! and others”; int count=0; for(int i=0;s[i]!=””;i++) count++; cout<<“Length of string s : “<<count; return 0; } Output Length of string s : 13 Print Page Previous Next Advertisements ”;
C++ String Concatenation
C++ String Concatenation ”; Previous Next String concatenation is the process of adding an element to an existing element. In this context, string concatenation is the method by which two (or more) strings can be added to one another. Hence, the resultant string is the combination of the initial string and the added string. There are several methods to concatenate strings in C++, some of which are given as follows − Using string::append() function Using ”+” operator Using strcat() function for C-style strings Using for loop Using while loop Using range based loop Using inheritance Using friend function with OOPS These methods are explained in detail in the next few articles of this chapter. So, let’s dive into these concepts. String Concatenation Using string::append() Function String is a class defined in <string> header file, and the append() function is an inherited method of that class. This method is used to append or add a given string to an initial string. Syntax The following syntax is used to concatenate string using the append() method − initial_string.append(new_string); initial_string.append(“this is new”); Parameters The string::append() function takes a string as a parameter. The string can be passed explicitly or as an object. Example of append() function The following exemplar code is used to concatenate string using the append() method − #include <iostream> using namespace std; int main() { string initial_string(“I Love TP.”); string new_string(” I am new here.”); //using append function with object parameter initial_string.append(new_string); //using append function with explicit string initial_string.append(” Could you help me?”); cout << initial_string << endl; return 0; } Output I Love TP. I am new here. Could you help me? String Concatenation Using ”+” Operator One of the easiest way to add strings is to use the ”+” operator on two or more strings. This can be done in place (i.e. without creating a new string), or in a new string object. This is one of the newer features of C++ programming language. Syntax The following syntax is used to concatenate string using the ”+” opertaor − new_string=initial_string+added_string; initial_string+=added_string Here, the new string can be added in place or by creating a new string object. Example The following exemplar code is used to concatenate string using the ”+” opertaor − #include <iostream> using namespace std; int main() { string initial_string(“I Love TP.”); string new_string(” I am new here.”); string a=”Hey !!! ” + initial_string; //using new string object a+=new_string; //inplace addition a+=” Could you help me? “; cout << a << endl; return 0; } Output Hey !!! I Love TP. I am new here. Could you help me? String Concatenation Using for Loop We can use a simple for loop from the beginning of the new string to the end of the new string, and for each iteration, we can add that character to the initial string. This can be done in place, or by using a new string object. This type of concatenation is also possible in C-style strings, which are character arrays. Syntax The following syntax is used to concatenate string using for loop from beginning of the string to the end − for(int i=0;i<s.length();i++){ initial+=s[i]; } Example The following exemplar code is used to concatenate string using for loop from beginning of the string to the end − #include <iostream> using namespace std; int main(){ string initial_string(“I Love TP.”); string new_string(” I am new here.”); for(int i=0;i<new_string.size();i++){ initial_string+=new_string[i]; } //using for loop to iterate over new_string cout << initial_string << endl; return 0; } Output I Love TP. I am new here. String Length Using while Loop We can also use a simple while loop. This loop runs till we reach the end of the string, and at each iteration, we can add the corresponding character to the initial string. This can be done in place, or by using a new string object. This type of concatenation is also possible in C-style strings, which are character arrays. Syntax The following syntax is used to concatenate string using while loop from beginning of the string to the end − for(int i=0;i<s.length();i++){ initial+=s[i]; } Example The following exemplar code is used to concatenate string using while loop from beginning of the string to the end − #include <iostream> using namespace std; int main() { string initial_string(“I Love TP.”); string new_string(” I am new here.”); int i=0; while(new_string[i]!=””){ initial_string+=new_string[i]; i++; } //using while loop to iterate over new_string cout << initial_string << endl; return 0; } String Concatenation Using range based loop We can also use a range based loop, which will automatically iterate over the whole string and we can add each character to the initial string. This can be done in place, or by using a new string object. Syntax The following syntax is used to concatenate string using range based loop from beginning of the string to the end − for(char c: s){ initial+=c; } Example The following exemplar code is used to concatenate string using range based loop from beginning of the string to the end − #include <iostream> using namespace std; int main() { string initial_string(“I Love TP.”); string new_string(” I am new here.”); for(char c: new_string){ initial_string+=c; } //using range based loop for concatentation cout << initial_string << endl; return 0; } Output I Love TP. I am new here. String Concatenation Using strcat() Function We can use strcat() function to concatenate strings in C++.
C++ Operators
Operators in C++ ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provide the following types of operators − Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators This chapter will examine the arithmetic, relational, 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 Example + Adds two operands A + B will give 30 – Subtracts second operand from the first A – B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 ++ Increment operator, increases integer value by one A++ will give 11 — Decrement operator, decreases integer value by one 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 Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is 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. (A >= B) is not 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. (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 Example && Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is 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. !(A && B) is true. Bitwise Operators Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 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 Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of ”flipping” bits. (~A ) will give -61 which is 1100 0011 in 2”s complement form due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111 Assignment Operators There are following assignment operators supported by C++ language − Show Examples Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C – A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand. C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand. C %= A is equivalent to C = C % A <<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator. C >>=
C++ Modifier Types
C++ Modifier Types ”; Previous Next C++ allows the char, int, and double data types to have modifiers preceding them. A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of various situations. The data type modifiers are listed here − 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 example, unsigned 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 int. It automatically implies int. For example, the following two statements both declare unsigned integer variables. unsigned x; unsigned int y; To understand the difference between the way signed and unsigned integer modifiers are interpreted by C++, you should run the following short program − Live Demo #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. Type Qualifiers in C++ The type qualifiers provide additional information about the variables they precede. Sr.No Qualifier & Meaning 1 const Objects of type const cannot be changed by your program during execution. 2 volatile The modifier volatile tells the compiler that a variable”s value may be changed in ways not explicitly specified by the program. 3 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. Print Page Previous Next Advertisements ”;
C++ Storage Classes
Storage Classes in C++ ”; Previous Next A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program auto register static extern mutable The auto Storage Class The auto storage class is the default storage class for all local variables. { int mount; auto int month; } The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables. The register Storage Class The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can”t have the unary ”&” operator applied to it (as it does not have a memory location). { register int miles; } The register should only be used for variables that require quick access such as counters. It should also be noted that defining ”register” does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. The static Storage Class The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable”s scope to be restricted to the file in which it is declared. In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class. Live Demo #include <iostream> // Function declaration void func(void); 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 the following result − i is 6 and count is 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i is 15 and count is 0 The extern Storage Class The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use ”extern” the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. First File: main.cpp #include <iostream> int count ; extern void write_extern(); main() { count = 5; write_extern(); } Second File: support.cpp #include <iostream> extern int count; void write_extern(void) { std::cout << “Count is ” << count << std::endl; } Here, extern keyword is being used to declare count in another file. Now compile these two files as follows − $g++ main.cpp support.cpp -o write This will produce write executable program, try to execute write and check the result as follows − $./write 5 The mutable Storage Class The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override const member function. That is, a mutable member can be modified by a const member function. Print Page Previous Next Advertisements ”;
C++ Basic Input/Output
C++ Basic Input/Output ”; Previous Next The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. 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. I/O Library Header Files There are following header files important to C++ programs − Sr.No Header File & Function and Description 1 <iostream> This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively. 2 <iomanip> This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision. 3 <fstream> This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter. The Standard Output Stream (cout) The predefined object cout is an instance of ostream class. The cout object is said to be “connected to” the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example. Live Demo #include <iostream> using namespace std; int main() { char str[] = “Hello C++”; cout << “Value of str is : ” << str << endl; } When the above code is compiled and executed, it produces the following result − Value of str is : Hello C++ The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values. The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line. The Standard Input Stream (cin) The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example. Live Demo #include <iostream> using namespace std; int main() { char name[50]; cout << “Please enter your name: “; cin >> name; cout << “Your name is: ” << name << endl; } When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result − 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; The Standard Error Stream (cerr) The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately. The cerr is also used in conjunction with the stream insertion operator as shown in the following example. Live Demo #include <iostream> using namespace std; int main() { char str[] = “Unable to read….”; cerr << “Error message : ” << str << endl; } When the above code is compiled and executed, it produces the following result − Error message : Unable to read…. The Standard Log Stream (clog) The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed. The clog is also used in conjunction with the stream insertion operator as shown in the following example. Live Demo #include <iostream> using namespace std; int main() { char str[] = “Unable to read….”; clog << “Error message : ” << str << endl; } When the above code is compiled and executed, it produces the following result − Error message : Unable to read…. You would not be able to see any difference in cout, cerr and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used. Print Page Previous Next Advertisements ”;
C++ Environment Setup
C++ Environment Setup ”; Previous Next Local Environment Setup If you are still willing to set up your environment for C++, you need to have the following two softwares on your computer. 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 example, 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. A text editor should be in place to start your C++ programming. C++ Compiler This is an 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 to 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 the respective Operating Systems. Installing GNU C/C++ Compiler UNIX/Linux Installation If you are using Linux or UNIX then check whether GCC is installed on your system by entering the following command from the command line − $ g++ -v If you have installed GCC, then it should print a message such as the following − Using built-in specs. Target: i386-redhat-linux Configured with: ../configure –prefix=/usr ……. Thread model: posix gcc version 4.1.2 20080704 (Red Hat 4.1.2-46) If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/ 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 website 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 MinGW, 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. Print Page Previous Next Advertisements ”;