Tokens
Smallest indivisible parts of a program are called lexemes and groups of similar lexemes are called tokens. C++ program contains several items and those are identified as tokens by a compiler. C++ tokens are as follows:
- Keywords
- Identifiers
- Constants
- Strings
- Operators
Keywords are words which are reserved by the compiler for specific purpose. Keywords cannot be used as identifiers in programs. Keywords available in C++ are as follows:
Identifiers are names given to variables, arrays, classes, functions, structures, etc.
Variables
What is a variable?
A variable is a placeholder or container in memory (RAM) for storing values. We can store different values in a variable at different points of execution. To use variables in a C++ program, we have to declare and initialize them.
Declaring a variable
Before using a variable in a program, we need to declare it. Syntax for declaring a variable is as follows:
data_type variable_name;
In the above syntax, data_type tells the compiler about the type of data (ex: integer, character etc..) that will be stored in the variable with the name variable_name.
Quite often we hear the term called definition. Defining a variable means specifying the amount of memory that the variable occupies. Above declaration syntax also defines the memory that will be allocated (based on data type) to variable_name.
An example for variable declaration is as follows:
int x;
In the above syntax, x is the variable name and int is a data type which tells the compiler that x can store integer values.
We can’t write variable names as we like. There are some restrictions that apply to writing variable names. They are:
- Variable name must start with a letter or an underscore.
- Variable names must not contain white spaces.
- Variable names must not contain any special symbols like $, @, # etc.
- Variable names must not be same as any keyword like if, while, struct
Initializing a variable
After declaring a variable, we can assign or store a value in it. This is known as variable initialization. Syntax for initializing a variable is as follows:
variable_name = value;
An example for initializing a variable is as follows:
x = 10;
We can combine variable declaration and initialization in to a single line as shown below:
data_type variable_name = value;
An example for declaring and initializing a variable in a single line is as follows:
int x = 10;
Note: If we don’t initialize a variable, it will contain garbage value. It is a good practice to initialize a variable to a default value when we declare it.
A small C++ program demonstrating the use of variables is given below. In this program we add two values by storing them in two variables.
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
cout<<"Enter a number: ";
cin>>num1;
cout<<"Enter another number: ";
cin>>num2;
cout<<"Sum of "<<num1<<" and "<<num2<<" is: "<<(num1+num2)<<endl;
return 0;
}
Input and output for the above program is as follows:
Enter a number: 10
Enter another number: 29
Sum of 10 and 29 is: 39
Scope of a variable
The scope of a variable tells the compiler in which statements of the program can a variable be accessed. Based on where the variable is declared, variables are divided into two types: local variables and global variables.
A local variable is a variable which is declared within a block (a block is a set of statements enclosed in between braces i.e { and }). The scope of a local variable is within the block in which it is declared. A block cannot have two or more local variables with the same name.
To demonstrate the scope of a local variable, consider the following program:
#include <iostream>
using namespace std;
int dosum(int x, int y)
{
return x+y;
}
int main()
{
int num1, num2;
cout<<"Enter a number: ";
cin>>num1;
cout<<"Enter another number: ";
cin>>num2;
cout<<"Sum of "<<num1<<" and "<<num2<<" is: "<<dosum(num1, num2)<<endl;
//cout<<"Sum of "<<num1<<" and "<<num2<<" is: "<<(x+y)<<endl;
return 0;
}
Input and output for the above program is as follows:
Enter a number: 4
Enter another number: 6
Sum of 4 and 6 is: 10
In the above program, dosum() is a function. Functions will be explained later. In dosum() function, variables x and y are local to that function. In main() function, variables num1 and num2 are local to that function.
Notice that in the above program the statement before return 0 line has been commented. If the comments are removed and compiled, you will see the following error messages:
Above error messages are displayed as the variables x and y are local to dosum() function and cannot be accessed in main() function.
Global Variables
A variable that is declared outside all blocks is called a global variable. The scope of a global variable is the entire program from the point at which it is declared. To demonstrate the scope of a global variable, consider the following program:
#include <iostream>
using namespace std;
int dosum(int x, int y)
{
//cout<<"global = "<<global<<endl;
return x+y;
}
int global = 10;
int main()
{
int num1, num2;
cout<<"Enter a number: ";
cin>>num1;
cout<<"Enter another number: ";
cin>>num2;
cout<<"Sum of "<<num1<<" and "<<num2<<" is: "<<dosum(num1, num2)<<endl;
cout<<"global = "<<global<<endl;
return 0;
}
Input and output of the above program is as follows:
Enter a number: 3
Enter another number: 8
Sum of 3 and 8 is: 11
global = 10
In the above program, global is a global variable and observe that it is declared after the dosum() function. The variable global is not accessible above the line at which it is declared. That is why the print statement inside the dosum() is commented out. Removing the comments will produce compilation error.
Data Types
A data type specifies the type of data that we can work with. As C++ is a strongly typed (not truly) language (type is specified before use), type of a variable must be specified before it is used. C++ provides several pre-defined data types. They are as shown in the following table:
Character data type
The char data type is used to work with single characters. An example of storing a character into a variable is as follows:
char ch = ‘s’;
In the above statement, ‘s’ is a character constant. Size of char type is 1 byte which can hold values from -127 to 127 and size of unsigned char is 1 byte which can hold values from 0 to 255. Since 256 values are not enough to represent all the characters across the world, C++ is not suitable for developing cross-language applications.
Integer data type
An integer data type is used to work with numbers that don’t have any fractional parts. Standard data type for working with integers is int. Size of int data type is generally 4 bytes. There are variations in int data type like short and long. All of these differ in terms of memory.
Another variation in integer types is signed and unsigned. In signed types, the Most Significant Bit (MSB) is reserved by specifying the sign (0 for positive and 1 for negative). In unsigned types, MSB is also used to represent data.
Floating point data type
A floating point type allows us to work with real numbers which have decimal point. Floating point types are float and double. For example to store the value of mathematical PI value, we can declare a variable as follows:
float PI = 3.1415;
For double precision floating point values, we can use double type.
Boolean data type
Boolean data type allows us to work with true and false values which are known as boolean values. These values can be used to maintain state, flag, available or unavailable kind of information.
C++ in the newer versions had provided support to work with boolean values by including bool data type. Below example demonstrates bool data type:
bool flag = true;
Can we declare variables without data type?
C++ allows programmers to declare variables without specifying the data type. Data type of such variables will be decided by the value that they are initialized to. Such variables should be declared using the keyword auto as shown below:
auto flag = false;
In the above statement the data type of flag variable will be assumed to be bool by the compiler based on the value false.
typedef keyword
The typedef keyword can be used to create convenient names (types) for pre-defined data types. Consider the following example which demonstrates the use of typedef keyword:
typedef float average;
In the above statement we are creating average as a type which is a substitute for the pre-defined type float. Now we can create variables using average type as shown below:
average avg;
Constants
While programming you might need to store certain values which do not change throughout the program. For example, in mathematical formulae for calculating the area and perimeter of a circle we need the value of PI to be same. Such values are maintained as constants.
A constant is similar to a variable in the sense it is a placeholder in memory. Only difference is value of a constant cannot be changed once initialized. Constants in C++ can be:
- Literal constants (ex: 2, 5.6, ‘a’, “hi” etc.)
- Declared constants (using const keyword)
- Constant expressions (using constexpr keyword)
- Enumerated constants (using enum keyword)
- Defined constants (using #define pre-processor directive. This is not recommended and is deprecated)
Literal Constants
Constants that are used directly in the programs without declaration are literal constants. Literal constants can be:
- Integer constants (ex: 5, 200, -4, etc.)
- Floating point constants (ex: 9.3, 0.3, 12.34343, etc.)
- Character constants (ex: ‘d’, ‘4’, ‘g’, ‘$’, etc.)
- String constants(ex: “a”, “hi”, “C++”, “my name”, etc.)
Declared Constants (const)
The most important and frequently used type of constants are constants which are declared using the keyword const. General syntax for declaring a constant using const keyword is as follows:
const data-type constant-name = value;
A constant should be initialized at the time of declaration itself. Let’s look at an example for declaring a constant using const keyword.
const double PI = 3.1415;
In the above example, PI is the constant name and its value is 3.1415. Following is a program which demonstrates the use of const keyword.
#include <iostream>
using namespace std;
const double PI = 3.1415;
double area(int r)
{
return PI*r*r;
}
double peri(int r)
{
return 2*PI*r;
}
int main()
{
int radius;
//PI = 3.142;
cout<<"Enter radius of the circle: ";
cin>>radius;
cout<<"Area of the circle is: "<<area(radius)<<endl;
cout<<"Perimeter of the circle is: "<<peri(radius)<<endl;
return 0;
}
Input and output for the above program is as follows:
Enter radius of the circle: 3.6
Area of the circle is: 28.2735
Perimeter of the circle is: 18.849
In the above example, area() and peri() are functions. We will look at functions later. Observe that in the above program, PI is a global constant as it is declared outside all blocks.
Also, the line after the statement int radius is commented. If you remove the comments, it will result in a compilation errors as constants cannot be initialized again after declaration. The error message will be as follows:
We can also assign our own values to the constants as demonstrated in the following program:
ConstDemo.cpp: In function ‘int main()’:
ConstDemo.cpp:15:5: error: assignment of read-only variable ‘PI’
Constants expressions (constexpr)
Using constexpr we can create constants whose value is determined by evaluating an expression at compile time. We can also use constexpr with functions, constructors and objects.
When used along with a function, it will be treated as an inline function which can improve the performance of the program. Following is an example which demonstrates the use of constexpr keyword:
#include <iostream>
using namespace std;
constexpr double PI = 22.0 / 7;
constexpr double area(int r)
{
return PI*r*r;
}
constexpr double peri(int r)
{
return 2*PI*r;
}
int main()
{
int radius;
cout<<"Enter radius of the circle: ";
cin>>radius;
cout<<"Area of the circle is: "<<area(radius)<<endl;
cout<<"Perimeter of the circle is: "<<peri(radius)<<endl;
return 0;
}
Input and output for the above program is as follows:
netaji@ubuntu:~/cpp$ g++ ConstDemo.cpp -std=c++11
netaji@ubuntu:~/cpp$ ./a.out
Enter radius of the circle: 3.56
Area of the circle is: 28.2857
Perimeter of the circle is: 18.8571
Note: constexpr was introduced in C++11 version. To enable g++ compiler to use C++11, we should use the flag “-std=c++11″. Otherwise when we compile the program, it will raise several errors.
Enumerated Constants (enum)
In some scenarios we might want a variable to have a limited set of values like days of a week or months in a year etc. For these situations we can use an enumerated constant which can be declared using the enum keyword. General syntax of creating enumerated constants is as follows:
enum constant-name{value1, value2, …, valueN};
An example of using enum is as follow:
enum days{Mon, Tue, Wed, Thu, Fri, Sat, Sun};
In the above example days is just like a variable but only accepts the given constant values. By default compiler assigns numeric value to each constant and the starting value is 0 and the subsequent constants are given previous value plus one. So, value of Mon is 0, Tue is 1, and so on.
#include <iostream>
using namespace std;
int main()
{
enum days{Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};
days bday = Fri;
cout<<"Day is: "<<bday<<endl;
return 0;
}
Output of the above program is as follows:
Day is: 5
In the above program Mon is assigned 1. So, value of Tue is 2 and so on. We can use the enumerated constant like a type and declare new variables. In the above example bday is such variable declared using the enumerated constant days.
Defined Constants (#define)
Another way of declaring constants is by using the #define pre-processor directive. This method of declaring constants is not recommended and is deprecated. Syntax for declaring a constant using #define is as follows:
#define Constant-Name Value
Notice that in the above syntax there is no semi-colon at the end of the statement. An example for using #define is as follows:
#define PI 3.1415
Following is a program which demonstrates the use of #define pre-processor directive:
#include <iostream>
#define PI 3.1415
using namespace std;
int main()
{
cout<<"Value of PI is: "<<PI<<endl;
return 0;
}
Output of the above program is as follows:
Value of PI is: 3.1415
Operators
It is common in programming to use various kinds of operations like addition, subtraction, multiplication etc. C++ supports wide variety of operators which can be broadly divided in to following categories:
- Arithmetic operators
- Relational operators
- Logical operators
- Bitwise operators
- Other operators
Assignment Operator
The assignment operator (=) is used to assign the value of an expression to a variable and can be used within any valid expression.
We need to know about two important terms frequently encountered in compiler error messages: lvalue and rvalue. Lvalue refers to the variable on the left hand side of the assignment operator and Rvalue refers to the expression on the right hand side of the assignment operator.
The expression on the right hand side can be a constant or a variable or a complex expression. Left hand side should never be a function or a constant.
Multiple variables can be assigned the same value using assignment operator as shown below:
int a, b, c;
a = b = c = 0;
Arithmetic Operators
Perhaps arithmetic operators are the most frequently used operators in programs. Arithmetic operators contains operators for performing addition, subtraction, multiplication, division and modulus (remainder). Remember that floating point values cannot be used along with modulus operator. Arithmetic operators are as follows:
Also increment (++) and decrement (–) operators are included in this category. Increment operator increments the value of operand by one and decrement operator decrements the value of the operand by one. Both of these operators are unary operators i.e they are used along with a single operand.
Increment and decrement operators can be used before or after the operand. If they are used before the operand, they are called as pre increment / decrement operator or if they are used after the operand, they are called as post increment / decrement operator.
In expressions, post and pre increment / decrement operators have different effects. Consider the following example:
a = 5;
b = a++;
While using post increment, value of the operand is fetched, used in the expression and then it is incremented. So, value of b is 5 in the above example. Now, consider another example:
a = 5;
b = ++a;
While using pre increment, value of the operand is fetched, incremented and then used in the expression. So, value of b is 6 in the above example.
Relational Operators
Whenever we want to compare two values or variables, we can use relational operators. These operators return true or false based on the values or variables used in the expression. Relational operators in C++ are as follows:
Sir also upload C Basics, Sorting techniques, Files in C
ReplyDeleteSir please upload DLD in GATE point of view
ReplyDeleteSir upload SE Rajiib Mall text book
ReplyDelete