C++
#
OverviewC++
is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language, or "C with Classes".
C++ is a complied language. C++ source files has the .cpp
extension.
info
C++ is a case-sensitive language.
- Lets write simple c++ program which will print
Hello World
on the screen.
In the above code
#include
is a preprocessor directive used to include the header files.iostream
is a header file for taking input or printing output.int
is type of data returned by function.main
is the function where execution of code begins in any c++ program.cout
is used for displaying output in quotation marks.;
marks the end of the statement.return 0
Exit status of the function.{}
define the start and end of the code block (main function here).
info
In C++
execution of code begins from main
function.
#
CommentsComments are lines that exist in computer programs that are ignored by compilers and interpreters.
Including comments in programs makes code more readable for users as it provides some information or explanation about what each part of a program is doing.
There are two types of comments in C++
- Single-line comments
//
anything after these//
is comment - Multi-line comments
/* */
anything in-between/* */
those asterisks is comment
- Single-line comments
#
VariablesVariable is an arbitrary name given to the memory location which is used to store some data (value) in computer program. The value stored in a variable can be changed.Variables are given unique names to differentiate between different memory locations.
Creating a variable is known as variable declaration and assigning some value to the variable is known as initialization.
#
Rules for declaring a variable name- Variable hold a single type of data hence we've to define the type of variable.
- Variable name must begin with a letter of alphabet or underscore.
- Variable name should not contain space or special characters.
- Variable name cannot be started with number but variable name can have number in between or end of the name.
- C++ keywords cannot be used as variable names.
warning
Variable names are case-sensitive.
#
Data TypesThere are three types of data types.
#
Primitive Data typesThese are the built-in data types. These are the basic data types which are used to represent the single value. Integer, Character, Float, Boolean.
#
Type ModifiersType Modifiers modify the size occupied by the given data type in memory or it can be used to increase the range by excluding negative values. They are long
(8 bytes), short
(2 bytes), signed
(4 bytes), unsigned
(4 bytes).
tip
Range of any N-bit signed integers was from to
1 Byte = 8 bits
Data Type | Size (Bytes) | Range |
---|---|---|
char | 1 | -128 to +127 |
short char | 1 | -128 to +127 |
unsigned char | 1 | 0 to 255 |
short int | 2 | -32768 to +32767 |
unsigned short int | 2 | 0 to 65535 |
int | 4 | -2147483648 to +2147483647 |
unsigned int | 4 | 0 to 4294967295 |
long int | 8 | -9223372036854775808 to +9223372036854775807 |
unsigned long int | 8 | 0 to 18446744073709551615 |
long long int | 8 | -9223372036854775808 to +9223372036854775807 |
unsigned long long int | 8 | 0 to 18446744073709551615 |
float | 4 | 1.17549e-38 to 3.40282e+38 |
float(negative) | 4 | -1.17549e-38 to -3.40282e+38 |
double | 8 | 2.22507e-308 to 1.79769e+308 |
double(negative) | 8 | -2.22507e-308 to -1.79769e+308 |
danger
Above values may vary from compiler to compiler. In the above example, we have considered GCC 32 bit.
For More Information Refer Here
#
Derived Data typesThese are derived from Primitive(built-in) data types. Like Array
, Function
, Pointer
and Reference
.
#
User-Defined Data typesThese are defined by users. Like, defining a class in C++ or a structure. Class
, Structure
, Union
, Enum
#
Basic Input Outputiostream
header file is used for taking input and printing output.
cout
is used to display on screen.
<<
is an insertion operator used along with cout
.
cin
is used to take input from the user.
>>
is an extraction operator used along with cin
.
#
OperatorsOperators are nothing but symbols that tell the compiler to perform some specific operations on the given operands.
#
Arithmetic OperatorsArithmetic operators perform some arithmetic operation on one or two operands.
Unary Operators are the operators that operate only on the one operand. ++
and --
unary operators.
Binary Operators operate onn two operands. +
, -
, *
, /
, %
are binary operators.
Lets assume x = 7
, y = 10
Operator | Operation | Example |
---|---|---|
+ | Addition of two operands | x + y = 17 |
- | Subtract second operand from first | y - x = 3 |
* | Multiplies two operands | x * y = 70 |
/ | Divides first operand by second | y / x = 1 |
% | Gives remainder after integer division | y % x = 3 |
++ | Increments value by one | x++ = 8 |
-- | Decrements value by one | x-- = 6 |
danger
Pre Increment/decrement (++x
) changes the values instantly where as Post Increment/decrement (x++
) changes the value only after completing the execution of current statement and before execution of next statement.
Simple example on arithmetic operators
#
Relational OperatorsRelational operators defines relation(comparision) between two operands and it returns boolean value.
Lets assume x = 7
, y = 10
Operator | Operation | Example |
---|---|---|
== | returns true if two operands are equal | x==y is false |
!= | returns true if two operands are not equal | x!=y is true |
> | returns true if left operand operand is greater than right operand | x==y is false |
< | returns true if left operand operand is less than right operand | x==y is false |
>= | returns true if left operand operand is greater than or equal to right operand | x==y is false |
<= | returns true if left operand operand is less than or equal to right operand | x==y is false |
Example on Relational Operators
#
Logical OperatorsLogical operators are used to combine multiple expressions/conditions together or to negate the logical value.
Lets assume x = 0, y = 1
Operator | Operation | Example |
---|---|---|
&& | Return true if both operands are non-zeros | x && y = false |
|| | Return true if any of the operands is non-zero | x && y = false |
! | Negate the logical value of the operand | !x = true |
#
Bitwise operatorsBitwise operators perform bit by bit operations.
Lets assume A = 0100 (4), B = 0101 (5)
Operator | Operation | Example |
---|---|---|
& (AND) | The result will contain 1 only if two bits are 1 | A&B = 0100 |
| (OR) | The result will contain 1 if 1 exist in atleast one of the opearnds | A | B = 0101 |
^ (XOR) | The result will contain one the two bits are different | A^B = 0001 |
~ | Binary ones complement. Flips the bits | ~A = 1011 |
<< | Left shift operator. Left operand bits are moved left by the number of places specified by the right operand. | A<< 1 = 1000 |
>> | Right shift operator. Left operand bits are moved right by the number of places specified by the right operand. | A>> 1 = 0010 |
tip
If shift operators applied on N then N<<a
will give a result and N>>a
will give a result
#
Assignment operatorsOperator | Operation | Example |
---|---|---|
= | Assigns value of right operand to left operand | A=B will put value of B in A |
+= | Adds right operand to the left operand and assigns the result to left operand. | A+=B A = A+B |
-= | Subtracts right operand from the left operand and assigns the result to left operand. | A-=B A=A-B |
*= | Multiplies right operand with the left operand and assigns the result to left operand. | A=B A=AB |
/= | Divides left operand with the right operand and assigns the result to left operand. | A/=B A=A/B |
#
Miscellaneous OperatorsOperator | Description | Example |
---|---|---|
sizeof() | Returns the size of a variable | sizeof(x) will return 4 since x is int |
condition ? x : y | Conditional operator. If condition is true, then returns value of x or else value of y | 2==3? 5 : 8 |
, | Comma Operator causes a sequence of operations to be performed | |
Cast | Cast Operator converts one data type to another | (int)3.14 would return 3 |
& | returns the address of a variable. | |
* | pointer to a variable. | *x will pointer to variable x |
-> and . | Member operators are used to reference individual members of classes, structures, and unions. |
#
Precedence of OperatorsCategory | Operator | Associativity |
---|---|---|
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
info
Unary, Conditional and Assignment operators have Right to Left associativity
#
Control FlowThe statements inside our source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code
#
If statementsIf we want to execute some code if and only if some condition is true then we use if statements.
#
If-Else statementsIf we want to execute the specific code block if the condition is true or else it'll execute the else code block. Above in examples of relational operators and logical operators we've already used if-else statements.
#
if-else-if ladderIf we've more than two alternatives to check and execute only one among them then we use if-else-if ladder
#
Nested-If-Else statementsHere we'll have the if-else statements within another if-else statement hence they're known as nested if-else statements.
#
Switch StatementSwitch statement is an alternative for the if-else-if ladder where it compares(equality) a variable with list of values. It looks much cleaner than the if-else-if ladder. If a choice must be made from one of several or more options, and the switch statement can be used, then the switch statement will likely be faster than the corresponding if-else ladder.
caution
The break
statement after switch cases
is used to avoid fallthrough in switch statement i.e. it will not executes all the remaining cases that exist after the true case.
#
While LoopLoop statements are used to execute the block of code repeatedly for a specified number of times (or) until it meets a specified condition. Loop statement are very useful to iterate over collection/list of items or to perform a task for multiple times.
While loop is used to iterate a block of code as long as test expression (condition) is true. For each iteration the test expression will be evaluated. While loop comes handy when number of iterations is unknown.
#
do-while loopdo-while loop is similar to the while loop but do-while loop will execute atleast once even the test expression (condition) is false. First it will execute the code block then evaluates the test expression.
#
for loopfor-loop is used when the number of iterations is known. It takes initialization expression, test expression and update expression. The initialization expression will be executed only once as it will act as the iterator, test expression and update expression will be evaluated or executed for each iteration once the test expression evaluates to false the loop will be terminated.
#
Break statementBreak statement inside any loop will terminate the execution of the loop contiaining it. If nested loop has the break statement then it will break only inner loop but not the outer loop
info
break statement is also used in switch statement to avoid fallthrough
#
Continue statementContinue satement inside any loop will skip the current iteration. When a continue statement will not terminate the loop rather it continues with next iteration.
#
Goto statementgoto statement is used to alter the normal execution of a program and transfer control (unconditionally) to a labeled statement in the same program. In a C++ program we can have multiple goto and label statements, the goto statement is followed by a label name.
info
Label is an identifier, which can be any plain text and can be set anywhere in a C++ program above or below to goto statement. When a goto statement is encountered, compiler transfers the control to a label: specified with goto statement and begin execution from there.
#
FunctionsIn computer language, a function is a block of code that performs a particular task, and it is given a name.
Functions in programming is similar to the mathematical functions. They take something as input, perform some operation on it, and return the output. Functions are reusable (define the code once and use it many times). Functions make the code modular.
info
In C++ the execution of code begins at main
function.
There are two types of functions
- Library functions: these are predefined
- User-defined functions: created by users
In C++ function creation consist of two steps. They are
- Function Declaration
- Function Definition
#
Function DeclarationFunction declaration informs the compiler about:
- The return type of function
- The function name
- The number of parameters and their data types.
Basic syntax of declaring a function is
#
Return TypeReturn Type specifies the type of data a function returns in output to the calling point after performing its task. Few functions doesn't return nothing in ouput such functions have void
return type.
#
Function ParametersParameters are nothing but the inputs we are passing to the function to perform some task using them. The parameters passed to function are called actual parameters or arguments. The parameters received by function are called formal parameters. Passing parameters in a function is optional.
While declaring the function it's not necessary to give parameter names but we've to mention the data type of parameter.
There are two ways to pass parameters. They are
- Pass by value: values of actual parameters are copied to functionโs formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of caller.
- Pass by reference: Both actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller.
#
Function definitionFunction definition contains the group of statements which will do specific task when the function is called.
In C/C++ function declaration and definition can be done at same place but it must be before the main function. Or else we declare the function before main function then we can define the defintion anywhere in the file or in any other module which was included in the program.
#
Calling a functionThe functions created in a program are not executed until we call them. When we call the function, control is given to the very first statement inside the called function. To call a function in a program, we have to write a function name followed by values of arguments in the round brackets and the semicolon. We can call a function in any other function in a program.
The basic syntax for calling a function is
Lets write a function which calculates area of the rectangle given length and breadth as input.
Another example where we write multiple functions for creating a simple calcuator
#
RecursionIf the function calls itself again and again until some condition is met, then such a function is known as a recursive function. This process is known as recursion.
Recursion follows the divide and conquer strategy. Where the given problem can be divided into sub-problems of itself. It helps us to write shorter code.
A recursive function consist of two cases they are
- Base case: The condition where the function stops calling itself in its body
- Recursive case: Which calls the function again and again until base conditino is met
Write a function to calculate factorial of given number
All recursive functions can be written using iteration(loops) which is faster compared to recursion since Recursive functions are expensive (inefficient) as they take up a lot of memory and time. Refer Recursion vs Iteration
#
ArraysAn array is a derived data type. An array is a sequential collection of values of the same data type under the same name are stored at contiguous memory locations. We must provide the size of an array while declaring. The values or elements of array can be accessed using index of the element. In C++ array index starts from 0.
Basic syntax of the array declaration
#
2D arraysTwo Dimensional array represents a matrix. Elements in 2D arrays can be accessed using row-index and column index.
Basic syntax of creating a 2D array
Write a function that will multiply the two matrices.
#
PointersPointers is a variable which stores the address of another variable instead of value. The address of a variable is in the hexa-decimal format which can be obtained using address-of operator &
.
info
The number that uniquely identifies the location in the memory is known as the memory address.
Syntax of pointer declaration and initialization.
Itโs a good practice to use ptr in a pointerโs variable name. It indicates that a variable is a pointer, and it must be handled differently.
The pointer will have the address of the variable. If we want to access the value present at that address then we'll use indirection or dereference operator *
. The dereference operator * is a unary operator. It gives the value of the variable to which the pointer is pointing. This process is known as dereferencing a pointer.
warning
A pointer must be valid before it is dereferenced. Dereferencing a null pointer or an uninitialized pointer causes undefined behavior. Your program might crash, but it might just as well keep running and start giving strange results.
#
Null PointerIf the pointer is pointing to nothing, then it will be initialized to nullptr. It is known as a null pointer. The value of the null pointer is 0.
caution
Dereferencing a null pointer (*p
) causes an STATUS_ACCESS_VIOLATION
exception
Simple pointer program
#
Reference VariableA reference is an alias, or an alternate name to an existing variable. The main use of references is acting as function formal parameters to support pass-by-reference. When an reference variable is passed into a function, the function works on the original copy (instead of a clone copy in pass-by-value). Changes inside the function are reflected outside the function. A reference is similar to a pointer. In many cases, a reference can be used as an alternative to pointer, in particular, for the function parameter.
&
is known as Reference operator or address-of operator based on the context (expression) it's used. When we declare a reference variable we do not create a new object in memory, we just declare alternate name for an existing variable. The original variable and reference variable are infact same memory location called by different names.
Reference variable syntax
info
After the reference relationship is established, it cannot be changed.
It shall be read as โnumber_ref is a reference to number, or โnumber_ref is an alias of numberโ. You can now refer to the variable as number_ref or number
#
References vs PointerPointers and references are equivalent, except:
Reference | Pointer |
---|---|
A reference must be initialized when it is declared. | A pointer can be initialized to any value anytime after it is declared. |
References cannot be NULL. | A pointer can be assigned to point to a NULL value. |
References can be used ,simply, by name. | Pointers need to be dereferenced with a * . |
Once a reference is initialized to a variable, it cannot be changed to refer to a variable object. | A pointer can be changed to point to any variable of the same type. |
#
Pass by reference in functionIn C/C++, by default, arguments are passed into functions by value (except arrays which is treated as pointers). That is, a clone copy of the argument is made and passed into the function. Changes to the clone copy inside the function has no effect to the original argument in the caller. In other words, the called function has no access to the variables in the caller.
#
With pointer argumentsIn many situations, we may wish to modify the original copy directly (especially in passing huge object or array) to avoid the overhead of cloning. This can be done by passing a pointer of the object into the function, known as pass-by-reference.
#
with Reference ArgumentsInstead of passing pointers into function, you could also pass references into function, to avoid the clumsy syntax of referencing and dereferencing.
note
Referencing (in the caller) and dereferencing (in the function) are done implicitly. The only coding difference with pass-by-value is in the function's parameter declaration.
Recall that references are to be initialized during declaration. In the case of function formal parameter, the references are initialized when the function is invoked, to the caller's arguments.
References are primarily used in passing reference in/out of functions to allow the called function accesses variables in the caller directly.
const
Function Reference/Pointer Parameters#
A const function formal parameter cannot be modified inside the function. Use const whenever possible as it protects you from inadvertently modifying the parameter and protects you against many programming errors.
A const function parameter can receive both const and non-const argument. On the other hand, a non-const function reference/pointer parameter can only receive non-const argument.
#
Passing the Function's Return Value#
Passing the Return-value as ReferenceYou can also pass the return-value as reference or pointer.
danger
You should not pass Function's local variable as return value by reference
This program has a serious logical error, as local variable of function is passed back as return value by reference. Local variable has local scope within the function, and its value is destroyed after the function exits. The GCC compiler is kind enough to issue a warning (but not error).
It is safe to return a reference that is passed into the function as an argument.
#
Passing Dynamically Allocated Memory as Return Value by ReferenceInstead, you need to dynamically allocate a variable for the return value, and return it by reference.
#
Dynamic Memory AllocationSometimes we need to create objects in memory during run time. This happens when we do not know the size of the object when we create and compile the program. Heap memory (also called free memory or dynamic memory) is used to store objects created during run time. This situation occurs when an object, or a collection of objects, needs a lot of memory or when the amount of memory cannot be calculated during the compilation. The objects created in heap memory cannot have a name, so to access them, we need a pointer in stack memory that can be pointed to them.
info
An object created in heap memory cannot have a name; it can be accessed only through its address, which is reached by a pointer in stack memory.
new
and delete
operators#
new
operator is used to allocate memory dynamically. new
operation returns a pointer to the memory allocated.
delete
operator is used to free the memory. The delete
operator takes a pointer (pointing to the memory allocated via new) as its sole argument.
note
Avoid using malloc()
and free()
from C. Instead, use new
and delete
, or new[]
and delete[]
.
To initialize the allocated memory, you can use an initializer for fundamental types, or invoke a constructor for an object.
new[]
and delete[]
Operators#
Dynamic array is allocated at runtime rather than compile-time, via the new[]
operator. To remove the storage, you need to use the delete[]
operator (instead of simply delete).
warning
To prevent memory leaks, every call to new
should be paired with a call to delete
, and every call to new[]
should be paired with a call to delete[]
. Not calling delete
or delete[]
, or mismatching calls, results in memory leaks.