Basic Grammar
A C++ program can be defined as a collection of objects that interact with each other by calling each other's methods. Now let's look briefly at what classes, objects, methods, and immediate variables are.
- Objects - Objects have state and behaviour. For example, a dog has a state - colour, name, breed, behaviour - wagging, barking, eating. An object is an instance of a class.
- Classes - Classes can be defined as a template/blueprint for describing the behaviour/state of an object.
- Methods - Basically, a method represents a behaviour. A class can contain multiple methods. It is possible to write logic, manipulate data and perform all actions in a method.
- Instant variables - Each object has its own unique instant variables. The state of an object is created from the values of these immediate variables.
Data typesโ
Built-in typesโ
type | keyword |
---|---|
integer | int |
float | float |
double | float |
null | void |
wide_character | wchar_t |
bool | |
character type | char |
Enumeration Typesโ
An enumeration type (enumeration) is a derived data type in C++ that is a collection of user-defined enumeration constants.
// To create an enumeration, use the keyword enum
enum enum-name { list of names } var-list;
// colour enumeration, the variable c is of type color
enum color { red, green, blue } c; c = blue;
// By default, the first name has a value of 0, the second name has a value of 1, the third name has a value of 2, and so on.
// But it is possible to assign a special value to a name, simply by adding an initial value.
// Here, blue has a value of 6, because by default each name will be 1 larger than the one before it.
enum color { red, green=5, blue }
Constant typesโ
Constants are fixed values that do not change during program execution. These fixed values are also called literals.
Constants can be of any basic data type and can be classified as integer numbers, floating point numbers, characters, strings and boolean values.
Constants are like regular variables, except that the value of a constant cannot be modified after it has been defined.
Definitionsโ
In C++, there are two simple ways of defining constants.
- Use the #define preprocessor.
- Using the const keyword.
Exampleโ
// #define preprocessor defined constants
#define identifier value
// The const prefix declares a constant of the specified type
const type variable = value;
Modifiersโ
C++ allows modifiers to be placed before char, int and double data types. The modifier is used to change the meaning of the base type, so it is better suited to a variety of contexts.
- signed
- unsigned
- short
- long
The modifiers signed, unsigned, long and short can be applied to integers, signed and unsigned to character types and long to double precision types.
The modifiers signed and unsigned can also be used as a prefix to the long or short modifiers. For example: unsigned long int.
Qualifiersโ
Type qualifiers provide additional information about a variable.
Qualifier | Meaning |
---|---|
const | const An object of type const cannot be changed by modification during program execution. |
volatile | The modifier volatile tells the compiler that the value of a variable may be changed in a way that is not explicitly specified by the program. |
restrict | A pointer modified by restrict is the only way to access the object it points to. Only C99 adds the new type qualifier restrict. |
typedefโ
You can use typedef to give a new name to an existing type.
typedef type newname;
// For example, the following statement would tell the compiler that feet is another name for int.
typedef int feet;
// Now the following statement is perfectly legal, and it creates an integer variable distance.
feet distance;
Types occupy bytesโ
C++ differs from Java in that the size of variables can vary depending on the compiler and the computer being used.
type | bit | range |
---|---|---|
char | 1 byte | -128 to 127 or 0 to 255 |
unsigned char | 1 byte | 0 to 255 |
signed char | 1 byte | -128 to 127 |
int | 4 bytes | -2147483648 to 2147483647 |
unsigned int | 4 bytes | 0 to 4294967295 |
signed int | 4 bytes | -2147483648 to 2147483647 |
short int | 2 bytes | -32768 to 32767 |
unsigned short int | 2 bytes | 0 to 65,535 |
signed short int | 2 bytes | -32768 to 32767 |
long int | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
signed long int | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
unsigned long int | 8 bytes | 0 to 18,446,744,073,709,551,615 |
float | 4 bytes | +/- 3.4e +/- 38 (~7 digits) |
double | 8 bytes | +/- 1.7e +/- 308 (~15 digits) |
long double | 8 bytes | +/- 1.7e +/- 308 (~15 digits) |
wchar_t | 2 or 4 bytes | 1 wide character |
// Output the size of the various data types on the computer
#include <iostream>
using namespace std;
int main(){
short int i; // Signed short integer
short unsigned int j; // unsigned short integer
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl; return 0;
}
Operatorsโ
An operator is a symbol that tells the compiler to perform a specific mathematical or logical operation. c++ has a rich set of operators built in, and provides the following types of operators.
- Arithmetic operators
- Relational operators
- Logical operators
- Bitwise operators
- assignment operators
- Miscellaneous Operators
Arithmetic Operatorsโ
Operators | Description | Instance |
---|---|---|
+ | Adding two operands together | A + B will give 30 |
- | subtracting the second operand from the first operand | A - B will give -10 |
| / | dividing the numerator by the denominator | B / A will give 2 | | % | The modulo operator, the remainder after integer division | B % A would give 0 | | ++ | Self-incrementing operator, increasing the integer by 1 | A++ will give 11 | | --- | Self-subtracting operator, decreases the integer by 1 | A-- will give 9 |
Relational Operatorsโ
operator | description | instance |
---|---|---|
== | Checks if the values of two operands are equal, and if so, the condition is true. | (A == B) is not true. |
! == = == Check if the values of the two operands are equal, or true if they are not. | (A ! = B) is true. | |
> | Check if the value of the left operand is greater than the value of the right operand, if so the condition is true. | (A > B) is not true. |
< | Checks if the value of the left operand is smaller than the value of the right operand, if so the condition is true. | (A < B) True. |
>= | Check if the value of the left operand is greater than or equal to the value of the right operand, if so the condition is true. | (A >= B) is not true. |
<= | Checks if the value of the left operand is less than or equal to the value of the right operand, and if so, the condition is true. | (A <= B) True. |
Logical Operatorsโ
operator | description | instance |
---|---|---|
&& | are called logical and operators. If both operands are non-zero, the condition is true. | (A && B) is false. |
| | is called the logical or operator. The condition is true if either of the two operands is non-zero. | |
! | is called the logical non-operator. It is used to reverse the logical state of an operand. If the condition is true then the logical non-operator will make it false. | ! (A && B) is true. |
Bitwise operatorsโ
operator | description | example |
---|---|---|
& | If present in both operands, the binary AND operator copies one bit to the result. | (A & B) will give 12, which is 0000 1100 |
| | If present in either operand, the binary OR operator is copied to the result. | (A | B) will give 61, which is 0011 1101 |
^ | If present in one of the operands but not both, the binary OR operator copies one bit to the result. | (A ^ B) will give 49, which is 0011 0001 |
The binary complement operator is a unary operator with a "flipped" bit effect, i.e. 0 becomes 1 and 1 becomes 0. | (~A ) will give -61, which is 1100 0011, the complement form of a signed binary number. | (~A ) |
<< | The binary left shift operator. The value of the left operand is shifted to the left by the number of bits specified by the right operand. | A << 2 will give 240, which is 1111 0000 |
>> | The binary right shift operator. The value of the left operand is shifted to the right by the number of bits specified by the right operand. | A >> 2 will give 15, which is 0000 1111 |
Assignment Operatorsโ
operator | description | example |
---|---|---|
= | A simple assignment operator that assigns the value of the right operand to the left operand | C = A + B will assign the value of A + B to C |
+= | The add-and-assign operator that assigns the right operand plus the left operand to the left operand | C += A is equivalent to C = C + A |
-= | The subtract-and-assign operator assigns the left operand minus the right operand to the left operand | C -= A is equivalent to C = C - A |
*= | The multiply-and-assign operator assigns the left operand the result of multiplying the right operand by the left operand | C = A is equivalent to C = C A |
/= | The divide and assign operator assigns the left operand to the left operand by dividing the left operand by the right operand | C /= A is equivalent to C = C / A |
%= | The modulo-and-assign operator that assigns the modulus of two operands to the left operand | C %= A is equivalent to C = C % A |
<<= | left shift and assignment operator | C <<= 2 is equivalent to C = C << 2 |
>>= | right shift and assignment operator | C >>= 2 is equivalent to C = C >> 2 |
&= | The sum-of-positions operator | C &= 2 is equivalent to C = C & 2 |
^= | The bitwise summation and assignment operator | C ^= 2 is equivalent to C = C ^ 2 |
|= | The bitwise or and assignment operator | C |= 2 is equivalent to C = C | 2 |
Miscellaneous Operatorsโ
operator | description |
---|---|
sizeof | The sizeof operator returns the size of a variable. For example, sizeof(a) would return 4, where a is an integer. |
condition ? X : Y | The condition operator. If Condition is true ? then the value is X : otherwise the value is Y. |
, | The comma operator performs a series of operations sequentially. The value of the entire comma expression is the value of the last expression in the comma-separated list. |
. (dot) and -> (arrow) | The member operators are used to refer to members of classes, structures and commons. |
Cast | The forced conversion operator converts one data type to another. For example, int(2.2000) would return 2. |
& | The pointer operator & returns the address of a variable. For example, &a; will give the actual address of the variable. |
* | The pointer operator * points to a variable. For example, *var; will point to the variable var. |
Operator precedenceโ
Category | Operators | Combinability |
---|---|---|
Suffix | () [] -> . ++ - - | left to right |
unary | + - ! ~ ++ - - (type)* & sizeof | right-to-left |
multiply & divide | * / % | left to right |
add and subtract | + - | left to right |
shift | << >> | left-to-right |
Relationships | < <= > >= | Left to right |
equal | == ! = | left to right |
bitwise AND | & | left-to-right |
bitwise or XOR | ^ | from left to right |
bitwise OR | | | left-to-right |
Logical AND | && | Left to right |
logical OR | | | |
conditional | ? : | right-to-left |
assignment | = += -= *= /= %=>>= <<= &= ^= |= | right-to-left |
comma | , | left-to-right |
Syntaxโ
Semicolonโ
C++ does not enforce code indentation, only a semi-colon to indicate the end of a statement.
// three different statements
x = y;
y = y+1;
add(x, y);
// Place a multi-line statement
x = y; y = y+1; add(x, y);
Spacesโ
In C++, spaces are used to describe whitespace, tabs, line breaks and comments. Spaces separate parts of a statement and allow the compiler to recognise where an element of the statement (such as int) ends and where the next element begins.
/*
* there must be at least one space character (usually a blank character) between int and age
* so that the compiler can distinguish between them.
*/
int age;
/*
* The space character between fruit and =, or = and apples is not required
* but for readability you can add as many spaces as necessary
*/
fruit = apples + oranges; // Get the total number of fruits
Identifiersโ
C++ identifiers are names used to identify variables, functions, classes, modules, or any other user-defined items.
An identifier starts with the letters A-Z or a-z or an underscore _ followed by zero or more letters, underscores and numbers (0-9).
Punctuation characters such as @, $ and % are not allowed inside C++ identifiers. c++ is a case-sensitive programming language. Therefore, in C++, Manpower and manpower are two different identifiers.
// Example identifiers
mohd zara abc move_name a_123myname50 _temp j a23b9 retVal
Statement blocksโ
A set of logically linked statements enclosed in curly brackets.
// block of statements
{
cout << "Hello World";
// output Hello World
return 0;
}
Commentsโ
C++ supports single line comments and multi-line comments. All characters in comments are ignored by the C++ compiler.
// Single line comments
/*
* Multi-line comments
*/
Keywordโ
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 |