Вы находитесь на странице: 1из 46

Origin of C++

Developed by Bjarne Stroustrup at Bell Labs in 1980s, as an extension of the C programming language by adding features from the language Simula 67. Initially called C with Classes. The name C++ was coined from the C increment operator ++. The major reason behind the success of C++ is that it uses object oriented technology.

Basic Elements of C++


First Program:

1 2 3 4 5 6

comment // first C++ program preprocessor directive #include <iostream> which namespace using namespace std; to use beginning of the function main int main() beginning of the body of main { cout << Welcome to C++!\n"; action (output) return 0; return 0 to operating system 7 } end of the body of main

Line 1 is a comment. A comment begins with a double slash // (single line comment). Comments are ignored by the compiler, but they immensely help in understanding the program. Line 2, #include <iostream>, is a preprocessor directive, which instructs the C++ system to include into the program the contents of the file name iostream. A line beginning with a pound sign (#) is a preprocessor directive. It is not considered to be a C++ statement and hence not terminated by a semicolon. (Every programming statement in C++ ends with a semicolon.)

A file whose name appears in #include directive is called a header file. Header files contain certain constants, variables, data types, or function declarations needed by a program. The input /output stream header file <iostream> contains declarations of input/output functions.

(Some other header files that are often used are :


#include <string>

#include <cmath>

etc.)

Line 3, using namespace std; , is to make the identifier cout (and cin) accessible to our program. The header file <iostream> (and in fact all standard header files) declares all of its identifiers to be in a namespace block called std. Line 4, int main(), is a part of every C++ program. The parentheses after main indicate that it is a function. Exactly one function in a C++ program must be main. In any C++ program, the program execution starts at main. The function main is, in a sense, the master function of any program.

The word int in main indicates that main is a value returning function that should return an integer value. In this program it returns 0. Line 5, {, indicates the start of the body of the function main. Every function body must start with the left brace, {. Line 6, cout << Welcome to C++!\n instructs the computer to perform an action in this case, output the string contained between the double quotation marks. The characters \n in line 6 is an escape sequence, denoting here the newline command.

The backslash character (\) is called an escape character and it indicates that a special character is to be output. Line 7, return 0, indicates that the function main returns value 0 to the operating system. It indicates here that the program has terminated successfully. Line 8, }, indicates the end of the body of the function main. Every function body must end with a right brace, }.

Some Special Characters


Character Name Description

// # <>

Double Slash Pound Sign Open, Close Brackets

Begins a comment Begins a preprocessor directive Encloses filename used in #include directive Used when naming function Encloses a group of statements Encloses a single character Encloses string of characters

() {} ""

Open, Close Parentheses Open, Close Braces Open, Close single quotes Open, Close Quote Marks

Semicolon

Ends a programming statement

Tokens, Identifiers and Keywords


A C++ program is a sequence of elements called tokens. A token is either an identifier, a punctuation symbol such as {, or an operator such as <<.
An identifier is a name associated with a function or a data object and used to refer to that function or data object. An identifier (name) is a sequence of letters, digits or underscores. An identifier must begin with a letter or an underscore. Normally an identifier name should not have length greater than 31.

C++ is case sensitive uppercase and lowercase letters are different. So, a1 and A1 are different identifiers. There are some identifiers which are reserved for specific uses in C++. Such identifiers are called keywords. For example, int, float, if are keywords. A keyword cannot be used as a programmer defined identifier. A declaration is a statement which introduces an identifier in a program along with its data type:
int year;

In C++, every identifier must be declared before it is used in the program.

Valid and invalid identifiers


Identifier totalSales total_Sales total.Sales
4thQtrSales

Valid ?
Yes Yes

Reason if invalid

No
No

totalSale$ as Class-mark Student,num


Student name

No No No No
No

Cannot contain period Cannot begin with a digit Cannot contain ($) Cannot use ()
Cannot use dash (-)

Cannot use comma


Cannot use space

Variables
A variable is a symbol that represents a memory location in computers memory. Different values may be stored at different times at this location. The content of a variable (memory location) is called the value of the variable. Declaring a variable means specifying a variable and its data type. A variable declaration has the following form:
(optional) data type variable name initializer
;

Examples:

int sum = 100; int count; char mychar; float average;

More than one variables of same type can be declared in the same line as a comma-separated list:
int count, firstnumber, secondnumber;
char mychar, char1, char2, initial; float height, weight, average;

A variable can be declared anywhere in the program but it must appear before it is used.

Since variables correspond to memory locations, therefore when an input command such as
cin >> number1;

is executed, the characters typed by the user are converted into the data type of number1 that is placed into memory location assigned to number1. When a new value is assigned to number1, it overwrites the previous value stored at that place. A variable name is any valid identifier that is not a keyword.

Constants
A constant is a location in the memory, referenced by an identifier, that cannot be changed . Examples:
const float PI = 3.14159; const int N = 100; const char BEEP = \b;

A constant must be initialized when it is declared.

Input/Output Streams
Output Stream object cout:
In C++, the output on the standard stream is performed using the cout output stream object. It requires iostream file for performing output. The information is sent to cout object using the output operator << (also known as put operator or stream insertion operator). << inserts the value of the variable on its right into the output stream that is named on its left. For example: cout << area;

More than one item can be displayed using a single cout object. Such outputs are called cascaded output operations. For example:
cout << Number = << number << endl;

The cout object displays all the items from left to right, hence the name stream.

Input Stream object cin: Standard input object. Like cout, requires iostream file. The input information is sent to cin using the input operator >> (also known as get operator or extraction operator). >> takes the value from the object named on its left and places it in the variable on its right. More than one item can be displayed using a single cin object. For example: cin >> number1 >> number 2;

Multiple input values from the keyboard must be separated by spaces or [Enter]. Multiple values may have different data types. User input goes from keyboard to the input buffer, where it is stored as characters. The cin object converts the data to the type that matches the variable
int number; cout << Enter the number "; cin >> number;

Spacing
Blank (white) spaces are ignored by the compiler except where needed to separate the identifiers, as in
int main()

However, a blank space is given output if it is part of some string . For example
cout << First number ;

Other exceptions:
A preprocessor directive must be written in a single line. A string constant cannot be broken into multiple lines.

Data Types
In C++, each piece of data must be of a specific data type. The data type determines how the data is represented in the computer and the kind of processing the computer can perform on it. C++ supports following classes of data types:
Primary (fundamental) data types, Derived data types, User defined data types.

C++ has following primary data types: Integral types: int, bool, char, short, long, etc.

Floating-point types: float, double, long double, etc. Derived data-types: arrays and pointers. User-defined data types: enumeration type, structures , and classes.

Integral Data Types: Represents an integer value a whole number without fractional part. C++ has following integral data types: char, short, int, long, bool By default an integral data type (except bool) is a signed integer, unless it is explicitly declared as unsigned, such as
unsigned int x;

All integral data types can be declared as unsigned, except bool. The data types char, short, int, and long are designed to represent different sizes of integers.

The following table shows memory sizes and the ranges of different integral data types. These values may be different for different machines.
Type Size in Bytes Minimum Value Maximum Value

char

-128
0 -32,768 0 - 231 0 - 263 0

127
255 32,767 65, 535 231- 1 232- 1 263- 1 264- 1

unsigned char 1 short 2 unsigned short int unsigned int long 2 4 4 8

unsigned long 8

Character Data Type char: Describes data consisting of one alpha -numeric character a letter, a digit, or a special symbol:
A, a, 5, +, $, *,

A char type is an integral type whose variables represent characters.


char c = A; cout << c = << c << endl; cout << int (c) = << int(c);

Output:
c = A int(c) = 65

Boolean Type: A bool data type is an integral type consisting of just two values, the constants true and false. These values are stored as 0 and 1 respectively. Example:
bool cout flag cout flag = false; << flag = << flag << endl; = true; << flag = << flag << endl;

Output:
flag = 0 flag = 1

Enumeration Data Type: An enumeration data type is a user defined data type. It is an integral type that has the syntax
enum typename{enumeration-list};

where enum is a keyword, typename is the identifier, and enumeration-list stands for a list of names for integer constants. For example :
enum color{red, blue, green};

We can then declare variables of this type:


color c1, c2;

and we can use them as simple data types:


if(c1==c2)cout << same colors<< endl;

C++ compiler treats enumeration types as consecutive integers. In the above example, the identifiers red, blue, and green are treated as 0, 1, and 2, respectively. For example, the following statements will produce output c = 1.
color c = blue; cout << c = <<c;

Constants values can explicitly be specified for the identifiers, such as


enum color{red=10, blue, green=20};

The enumerator blue will be assigned value 11.


Several different enumerators can be given same value:
enum color{red = 0, blue = 0, green = 2};

Floating Point Data Types: Used to represent floating point numbers . In C++, there are three types of floating point data types: float, double (double precision), and long double (extended double precision).
Memory sizes and ranges of floating point data types:
Type float double long double Size in Bytes 4 8 10 Minimum Positive value 3.4 E - 38 1.7 E -308 3.4 E - 4932 Maximum Positive Values 3.4 E +38 1.7 +308 1.1 E +4932

Arithmetic Operators and Expressions


Expressions are made up of constants, variables, and operators. C++ has following arithmetic operators: Unary plus +, such as +x; Unary minus -, such as x; Addition +, such as x + y; Subtraction -, such as x y; Multiplication *, such as x*y; Division /, such as x/y; (floating point division, integer division) Modulus % (remainder from integer division).

The first two operators are unary. The remaining operators are all binary operators. Division, such as 5/0, and modulus, such as 5%0, both produce errors. In floating point division, an expression such as 5.0/0.0 produces a special infinity value inf. The modulus operation can be performed only with the integers. Modulus operation on non integer operands is a compilation error. Arithmetic expressions in C++ must be entered into the computer in a straight line form. Parentheses in C++ expressions are used in the same manner as in algebraic expressions, e. g., a*(b + c).

Rules of Operator Precedence: Expressions within parentheses are evaluated first. In case of nested parentheses, the innermost pair of parentheses is applied first. Multiplication, division, and modulus operations are applied next. In case of several such operations, operators are applied from left to right. Additions and subtractions are applied last. In case of several additions or subtractions, operators are applied from left to right.

Relational Operators
A relational operator is used to make comparison between two expressions. These operations are binary. In C++, we have following relational operators:
Operator Meaning Sample conditions

< > <= >= ==

Less than Greater than Less than or equal to Greater than or equal to Equal to

x < y x > y x <= y x >= y x == y

!=

Not equal to

x != y

Reversing the pair of symbols in a relational operator is normally a syntax error. Confusing the equal to operator == with the assignment operator = results in a logical error. Sample C++ statements:
if (number1 < number 2) cout << number1 << < << number2; if (number1 == number 2) cout << number1 << == << number2;

(etc.)

Assignment Operators
The assignment operator, =, evaluates the expression on the right and assigns the resulting value to the variable on its left. In an arithmetical expression, the assignment operator has lowest precedence and it associates from right to left. Thus, an expression of the form x = y = 0 will first assign 0 to y and then assign the result of that assignment (0) to x. Other than the assignment operator = , C++ provides several compound assignment operators for abbreviating assignment operations.

For example, the statement c = c + 3;

can be abbreviated with the addition assignment operator += as c += 3;


In general, any statement of the form
variable = variable operator expression;

in which the same variable appears on both sides of the assignment operator and operator is one of the binary operator +, -, *, /, or, %, can be written in the form
variable operator= expression;

Examples: c d e f g

+= -= *= /= %=

5; 4; 3; 4; 7;

for c for d for e for f for g

= = = = =

c d e f g

+ 5; -4; * 3; / 4; % 7;

Increment and Decrement Operators


C++ also provide two unary operations for adding 1 or subtracting 1 from the value of a numeric variable. These are the unary increment operator , ++, and the unary decrement operator, --. Each of these two operators can be used as prefix or postfix, and their meaning changes accordingly. When used as a prefix, the value of the variable is incremented/decremented before being used in the expression in which it resides. But when used as postfix, its value is first used in the expression and then the value is incremented/ decremented.

These operators are summarized below:


Operato Called r ++ Sample Explanation Expressio n Preincreme ++a Increment a by 1, then use the new nt value of a in the expression in which a resides. a++ Post Use current value of a in the expression increment in which a resides, then increment a by 1. Predecreme --a Decrement a by 1, then use the new nt value of a in the expression in which a resides. Postdecrem a-Use current value of a in the expression ent in which a resides, then decrement a by 1.

++

--

--

When a variable is incremented or decremented in a statement by itself, then the preincrement (predcrement) and postincrement (postdecrement) have the same effect. For example ++m; and m++; will produce the same result. However, the statements a = ++b; and a = b++; will produce different results. In the first case, b is incremented first and then its new value is assigned to a. In the second case, the current value of b is assigned to a and then the value of b is incremented.

Type Conversion
Type coercion: Type coercion is automatic conversion of an operand from one data type to another data type.
int x = 4.5;

float x =(int y)*(float z);

Integer values and floating point values are stored differently in computers memory only the corresponding type of data can be stored for a defined variable. If an integer value is assigned to a variable declared as a float variable, the computer implicitly converts the integer value into a floating point number, or vice-versa.

For example:
int number = 4.5; cout << number;

will produce the output 4.

Type promotion:
Conversion of an operand with lower data type into one in a higher data type. Type demotion: Conversion of an operand with higher data type into one in a lower data type.

Generally, mathematical expressions, consisting of mixed data types lead to type coercion:
int number1, number2; float average; average = (number1 + number2)/2.0;

Coercion Rules: char, short, unsigned int, short are automatically promoted to int. When operating on values of different data types, the lower one is promoted to the type of the higher one. When using the assignment operator, = , the type of expression on right will be converted to type of variable on left.

Type-Casting: To make a program clear and error-free, we can use type casting , which is an explicit type conversion. A C++ cast operation consists of a data type and then, within parentheses the expression to be converted:
average = float(number1 + number2)/float(2); num1 = int(average);

In C++, the type casting operations come in three forms:


intVar intVar intVar = int(floatVar); = (int)floatVar; = static_cast<int>(floatVar);

The first form is called the functional notation, the second one is called the prefix notation, and the third one is the keyword notation.

The use of keyword casting is recommended. The functional notation has a limitation: the data type name must be a single identifier.
intVar = unsigned int(floatVar); //Not allowed intVar = (unsigned int)floatVar; //Yes intVar = static_cast<unsigned int>(floatVar);//Yes

Integer Division: When a number of type int is divided by a non zero number of type int, the result is always an integer. To find a floating point value in a division, at least one of the numbers should be of type float.

Therefore, if an accurate result in a division of integers is required, at least one of the operands must be casted to float. Example:
int a, b; \\ b not 0 float c = float(a)/float(b); float c = float(a)/b; float c = a/float(b);

OR OR

If one operand is a constant integer, then we can use its floating point value to get the correct division:
int a; float c = a/5.0;

Вам также может понравиться