C++ base
C++ base
Syntax refers to the rules and regulations for writing statements in a programming language. They
can also be viewed as the grammatical rules defining the structure of a programming language.
The C++ language also has its syntax for the functionalities it provides. Different statements have
different syntax specifying their usage, but C++ programs also have basic syntax rules that are
followed throughout all the programs.
We can learn about basic C++ Syntax using the following program.
#include <iostream>
// Standard Namespace
// Main Function
int main()
// Declaration of Variable
// Output
// Return Statement
return 0;
}
Output
58
The program above shows the basic C++ program that contains header files, main function,
namespace declaration, etc. Let’s try to understand them one by one.
1. Header File
The header files contain the definition of the functions and macros we are using in our program.
In line #1, we used the #include <iostream> statement to tell the compiler to include
an iostream header file library which stores the definition of the cin and cout standard input/output
streams that we have used for input and output. #include is a preprocessor directive using which we
import header files.
2. Namespace
A namespace in C++ is used to provide a scope or a region where we define identifiers. In line #2, we
have used the using namespace std statement for specifying that we will be the standard namespace
where all the standard library functions are defined.
3. Main Function
In line #3, we defined the main function as int main(). The main function is the most important part
of any C++ program. The program execution always starts from the main function. All the other
functions are called from the main function. In C++, the main function is required to return some
value indicating the execution status.
4. Blocks
Blocks are the group of statements that are enclosed within { } braces. The body of the main function
is from line #4 to line #9 enclosed within { }.
5. Semicolons
As you may have noticed by now, each statement in the above code is followed by a ( ; ) semicolon
symbol. It is used to terminate each line of the statement of the program.
6. Identifiers
We use identifiers for the naming of variables, functions, and other user-defined data types. An
identifier may consist of uppercase and lowercase alphabetical characters, underscore, and digits.
The first letter must be an underscore or an alphabet.
7. Keywords
In the C++ programming language, there are some reserved words that are used for some special
meaning in the C++ program. It can’t be used for identifiers. For example, the words int, return, and
using are some keywords used in our program.
#include <iostream>
class Calculate {
// Access Modifiers
public:
// data member
// member function
void addition() {
};
int main() {
// object declaration
Calculate add;
add.addition();
return 0;
Output
80
1. Class
A class is a user-defined data type. A class has its own attributes (data members) and behavior
(member functions). In line #3, we have declared a class named Calculate and its body expands
from line #3 to line #7.
The attributes or data in the class are defined by the data members & the functions that work on
these data members are called the member functions.
In the above example, num1 and num2 are the data member & addition() is a member function that
is working on these two data members. There is a keyword here public that is access modifiers.
The access modifier decides who has access to these data members & member functions.
3. Object
The object is an instance of a class. The class itself is just a template that is not allocated any
memory. To use the data and methods defined in the class, we have to create an object of that class.
C++ Loops
In C++ programming, sometimes there is a need to perform some operation more than once or
(say) n number of times. For example, suppose we want to print “Hello World” 5 times. Manually,
we have to write cout for the C++ statement 5 times as shown.
#include <iostream>
int main() {
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Let’s say you have to write it 20 times (it would surely take more time to write 20 statements) now
imagine you have to write it 100 times, it would be really hectic to re-write the same statement again
and again. In this case, loops come into use allowing users to repeatedly execute a block of
statements.
#include <iostream>
int main() {
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
In C++ programming, a loop is an instruction that is used to repeatedly execute a code until a certain
condition is reached. They are useful for performing repetitive tasks without having to write the
same code multiple times.
Loops can be classified on the basis of the sequency in which they check the condition relative to the
execution of the associated block of code.
1. Entry Controlled loops: In this type of loop, the test condition is tested before entering the
loop body.
2. Exit Controlled Loops: In this type of loop, the test condition is tested or evaluated at the
end of the loop body. Therefore, the loop body will execute at least once, irrespective of
whether the test condition is true or false.
Table of Content
for Loop
while Loop
do while Loop
for Loop
A for loop is a repetition control structure that allows us to write a loop that is executed a specific
number of times. It is an entry-controlled loop that enables us to perform n number of steps
together in one line.
Syntax
Test Condition: This specifies the test condition. If the condition evaluates to true, then body
of the loop is executed, and loop variable is updated according to update expression. If
evaluated false, loop is terminated.
Update Expression: After executing the loop body, this expression increments/decrements
the loop variable by some value.
Example
#include <iostream>
return 0;
Output
12345
The initialization and updation statements can perform operations unrelated to the condition
statement, or nothing at all – if you wish to do. But the good practice is to only perform
operations directly relevant to the loop.
A variable declared in the initialization statement is visible only inside the scope of the for
loop and will be released out of the loop.
Don’t forget that the variable which was declared in the initialization statement can be
modified during the loop, as well as the variable checked in the condition.
There is a type of for loop that does not need the condition and updation statement. It is
called range based for loop and it can only be used for iteratable objects such as vector, set, etc. For
a vector named v, it can be written to print its elements as:
#include <bits/stdc++.h>
int main() {
vector<int> v { 1, 2, 3, 4, 5};
return 0;
Output
12345
while Loop
While studying for loop, we have seen that the number of iterations is known beforehand, i.e. the
number of times the loop body is needed to be executed is known to us. while loop is used in
situations where we do not know the exact number of iterations of the loop beforehand. It is an
entry-controlled loop whose execution is terminated on the basis of the test conditions.
Syntax
while (condition) {
// Body of the loop
update expression
}
Example
#include <iostream>
int main() {
// Initialization
int i = 1;
while (i <= 5) {
i++;
return 0;
Output
12345
do while Loop
The do-while loop is also a loop whose execution is terminated on the basis of test conditions. The
main difference between a do-while loop and the while loop is in the do-while loop the condition is
tested at the end of the loop body, i.e. do-while loop is exit controlled whereas the other two loops
are entry-controlled loops. So, in a do-while loop, the loop body will execute at least
once irrespective of the test condition.
Syntax
do {
// Body of the loop
// Update expression
} while (condition);
Like while loop, only the condition is the part of do while loop syntax, we have to do
the initialization and updation manually outside and inside the loop respectively.
Example
#include <iostream>
int main() {
// Initialization
int i = 1;
// Updation
i++;
return 0;
Output
12345
Infinite Loops
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional
exit so that it repeats indefinitely. An infinite loop occurs when a condition is always evaluated to be
true. Usually, this is an error. We can manually create an infinite loop using all three loops:
#include <iostream>
int main() {
// expression is blank
for (;;) {
return 0;
Output
This loop will run forever.
This loop will run forever.
...................
#include <iostream>
int main() {
while(1) {
return 0;
Output
#include <iostream>
int main() {
do {
}while(1);
return 0;
}
Output
if in C++
if-else in C++
if-else if Ladder in C++
1. if Statement
In C++, the if statement is the simplest decision-making statement. It allows
the execution of a block of code if the given condition is true. The body of the if
statement is executed only if the given condition is true.
Syntax of if
if (condition) {
// Statements to execute if
// condition is true
}
Here if the condition is true then the code inside the if block will be executed
otherwise not.
Flowchart of if
Example of if
The below example demonstrates the use of the if statement by finding if the
age of a person is greater than 18 or not. if the condition is true then he/she is
allowed to vote.
#include <iostream>
using namespace std;
int main() {
int age = 19;
Output
allowed to vote
2. if-else Statement
The if else is a decision-making statement allows us to make a decision based
on the evaluation of a given condition. If the given condition evaluates to true
then the code inside the 'if' block is executed and in case the condition is false,
the code inside the 'else' block is executed.
Syntax of if-else
if (condition) {
// Executes this block if
// condition is true
}
else {
// Executes this block if
// condition is false
}
Flowchart of if-else
Flow diagram of if else
Example of if-else
The below example demonstrates the use of an if-else statement to find if the
given number is positive or nonpositive.
#include <iostream>
using namespace std;
int main() {
int n = 5;
Output
number is positive.
3. if else if Ladder
The if else if Ladder statements allow us to include additional situations after
the preliminary if condition. The 'else if' condition is checked only if the above
condition is not true, and the `else` is the statement that will be executed if
none of the above conditions is true. If some condition is true, then no only the
associated block is executed.
Syntax if else if Ladder
if (condition1) {
// Statements 1
}
else if (condition2) {
// Statements 2
}
else {
// Else body
}
We can use multiple else if statements with an if-else pair to specify different
conditions.
Flowchart of if-else-if Ladder
int main() {
int age = 18;
// if this condition is true child is printed
if (age < 13) {
cout << "child";
}
Output
Growing stage
4. Nested if else
The nested if else statement contains an 'if' statement inside another 'if'
statement. This structure lets in more complex selection-making by way of
comparing multiple conditions. In this type of statement, multiple conditions
are checked, and then the body of the last if statement is executed.
Syntax of Nested if else
if(condition1) {
// Code to be executed
if(condition2) {
// Code to be executed
}
else {
// Code to be executed
}
}
else {
// code to be executed
}
Flowchart of Nested if else
int main() {
int n = 44;
// to check if n is positive
if (n > 0) {
Output
positive and even number
5. Switch Statement
int main() {
char c = 'B';
switch (c) {
Output
6. Ternary Operator ( ? : )
The conditional operator is also known as a ternary operator. It is used to
write conditional operations provided by C++. The '?' operator first checks the
given condition, if the condition is true then the first expression is executed
otherwise the second expression is executed. It is an alternative to an if-else
condition in C++.
Syntax of Ternary Operator
expression ? statement_1 : statement_2;
Flowchart of Conditional Operator
Flow Diagram of Conditional operator
Example of Ternary Operator
The below program demonstrates the use of a conditional operator to find the
maximum of two numbers.
#include <iostream>
using namespace std;
int main() {
int num1 = 10, num2 = 40;
int max;
Output
40
7. Jump Statements
Jump statements are used to alter the normal flow of the code. If you want to
break the flow of the program without any conditions, then these jump
statements are used. C++ provides four types of jump statements.
A) break
break is a control flow statement that is used to terminate the loop and switch
statements whenever a break statement is encountered and transfer the
control to the statement just after the loop.
break statement is generally used when the actual number of iterations are
not predefined, so we want to terminate the loop based on some conditions.
Example
The below example demonstrates the use of breaks to manage the control
flow.
// C++ program to use break statement to break the loop when
// i become 3
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
// if i become 3 then break the loop and move to
// next statement out of loop
if (i == 3) {
break;
}
cout << i << endl;
}
// next statements
return 0;
}
Output
0
1
2
B) continue
The continue statement is used to skip the loop body for the current iteration
and continue from the next iteration. Unlike the break statement which
terminates the loop completely, continue allows us just to skip one iteration
and continue with the next iteration.
Example
The below example demonstrates the use of continue to manage the control
flow.
// C++ program to use continue statement to continue the
// loop when i become 3
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
// if i become 3 then skip the rest body of loop and
// move next iteration
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
Output
0
1
2
4
C) goto
It is a jump statement that is used to transfer the control to another part of the
program. It transfers the control unconditionally to the labeled statement.
Syntax
goto label;
// ...
label:
// Statement or block of code
Example
The below example demonstrates the use of the goto statement.
// C++ program to demonstrate the use of goto statement
#include <iostream>
using namespace std;
int main()
{
Output
You are not eligible to vote!
Note Use of goto is generally avoided in modern programming practices because
it may disturb the readability of the code and make the code error-prone,
although it is still valid and used occasionally.
D) return
The return statement is used to exit the function immediately and optionally
returns a value to the calling function. It returns to the function from where it
was called and if it is the 'main' function then it marks the end of the
execution. So basically, return is a mechanism used to communicate the
results back to the calling function.
Example
The below example demonstrates the use of a return statement to return a
value from a function.
// C++ program to use return statement to return the sum
// calculated by a function
#include <iostream>
using namespace std;
int main()
{
int res = add(3, 5);
cout << "The sum is: " << res << endl;
return 0;
}
Output
The sum is: 8
Logical OR Operator ( || )
Example
#include <iostream>
int main() {
else {
return 0;
}
Output
Student
2. Logical OR Operator ( || )
Syntax
expression1 || expression2
Example
#include <iostream>
int main() {
int n = 7;
else {
return 0;
Output
Operand 1 Result
true false
false true
Syntax
! expression
Example
#include <iostream>
int main() {
else {
return 0;
Output
If we assign a float value to a character value, then the compiler generates an error.
In the same way, if we try to assign any other value to the enumerated data types,
the compiler generates an error. Enumerator types of values are also known as
enumerators. It is also assigned by zero the same as the array. It can also be used
with switch statements.
Syntax:
enum enumerated-type-name
};
For Example: If a gender variable is created with the value male or female. If any
other value is assigned other than male or female then it is not appropriate. In this
situation, one can declare the enumerated type in which only male and female
values are assigned.
Enum in C++
The enum keyword is used to declare enumerated types after that enumerated type
name was written then under curly brackets possible values are defined. After
defining Enumerated type variables are created.
Enumerators can be created in two types:-
1. It can be declared during declaring enumerated types, just add the name of
the variable before the semicolon. or,
2. Besides this, we can create enumerated type variables as the same as the
normal variables.
By default, the starting code value of the first element of the enum is 0 (as in the
case of the array). But it can be changed explicitly.
Example:
Also, The consecutive values of the enum will have the next set of code value(s).
Example:
In this case,
first_enum e;
e=value3;
cout<<e;
Output:
11
Example:
C++
#include <bits/stdc++.h>
int main()
case Male:
break;
case Female:
break;
default:
return 0;
Output:
Gender is Male
#include <bits/stdc++.h>
enum year {
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec
};
// Driver Code
int main()
int i;
return 0;
Output:
0 1 2 3 4 5 6 7 8 9 10 11
C++ Functions
Functions are used to perform certain actions, and they are important for reusing
code: Define the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute
code. But you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function,
followed by parentheses ():
Syntax
void myFunction() {
// code to be executed
}
Example Explained
void means that the function does not have a return value. You will learn more
about return values later in the next chapter
inside the function (the body), add code that defines what the function should
do
Call a Function
Declared functions are not executed immediately. They are "saved for later
use", and will be executed later, when they are called.
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Declaration: the return type, the name of the function, and parameters (if
any)
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error
However, it is possible to separate the declaration and the definition of the function -
for code optimization.
You will often see C++ programs that have function declaration above main(), and
function definition below main(). This will make the code better organized and easier
to read:
Example
// Function declaration
void myFunction();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
The following example has a function that takes a string called fname as parameter.
When the function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the function, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.
In C++, data can be sent to functions when they are called in order to perform
operations. This data is called parameters or arguments and there are various
parameter passing methods available in C++. In this article, we will discuss various
parameter-passing techniques in C++.
Before you see the techniques, first understand the difference between the following
terms:
There are 3 different methods using which we can pass parameters to a function in
C++. These are:
Table of Content
Pass by Value
Pass by Reference
Pass by Pointer
1. Pass by Value
In pass by value method, a variable's value is copied and then passed to the
function. As the result, any changes to the parameter inside the function will not
affect the variable's original value in the caller. This method is simple, easy to
understand and implement but it is not preferred for large size of data structures at it
involves copying the value.
Example:
#include <iostream>
void change(int a) {
// Modifying arguments
a = 22;
int main() {
int x = 5;
change(x);
cout << x;
return 0;
Output
In this program, when the change function is called with x as the argument, a copy
of x is created and passed to the function. Inside the function, the parameter a is
modified, but this modification only affects the local copy of the value, not the original
variable x, as demonstrated by the output.
2. Pass by Reference
Example
#include <iostream>
void change(int& a) {
// Modifying arguments
a = 22;
int main() {
int x = 5;
change(x);
cout << x;
return 0;
Output
22
As we can see, the original value is modified. Just declaring the parameter a as a
reference changes it from pass by value to pass by reference.
3. Pass by Pointer
Example
#include <iostream>
// Modifying arguments
*a = 22;
int main() {
int x = 5;
change(&x);
cout << x;
return 0;
Output
22
Return Values
The void keyword, used in the previous examples, indicates that the function should
not return a value. If you want the function to return a value, you can use a data type
(such as int, string, etc.) instead of void, and use the return keyword inside the
function:
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
int main() {
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
Example
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
Function overloading allows you to define multiple functions with the same name but
different parameters.
The parameters should follow any one or more than one of the following conditions
for Function overloading:
add(int a, int b)
add(double a, double b)
#include <iostream>
// Driver code
int main()
add(10, 2);
add(5.3, 6.2);
return 0;
Output
sum = 12
sum = 11.5
add(int a, int b)
add(int a, int b, int c)
#include <iostream>
// Driver code
int main()
add(10, 2);
add(5, 6, 4);
return 0;
Output
sum = 12
sum = 15
add(int a, double b)
add(double a, int b)
#include<iostream>
cout<<"sum = "<<(a+b);
cout<<endl<<"sum = "<<(a+b);
// Driver code
int main()
add(10,2.5);
add(5.5,6);
return 0;
Output
sum = 12.5
sum = 11.5
#include <iostream>
void print(int i) {
void print(double f) {
int main() {
print(10);
print(10.10);
print("ten");
return 0;
Output
Here is int 10
#include<iostream>
cout<<"sum ="<<(a+b);
cout<<endl<<"sum ="<<(a+b+c);
main()
add(10,2);
add(5,6,4);
return 0;
}
#include<iostream>
cout<<"sum ="<<(a+b);
cout<<endl<<"sum ="<<(a+b);
main()
add(10,2.5);
add(5.5,6);
return 0;
Inline Functions
C++ provides inline functions to reduce the function call overhead. An inline function
is a function that is expanded in line when it is called. When the inline function is
called whole code of the inline function gets inserted or substituted at the point of the
inline function call. This substitution is performed by the C++ compiler at compile
time. An inline function may increase efficiency if it is small.
Syntax:
3. If a function is recursive.
4. If a function return type is other than void, and the return statement doesn’t
exist in a function body.
When the program executes the function call instruction the CPU stores the memory
address of the instruction following the function call, copies the arguments of the
function on the stack, and finally transfers control to the specified function. The CPU
then executes the function code, stores the function return value in a predefined
memory location/register, and returns control to the calling function. This can
become overhead if the execution time of the function is less than the switching time
from the caller function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of the
function call is usually insignificant compared to the amount of time the function
takes to run. However, for small, commonly-used functions, the time needed to make
the function call is often a lot more than the time needed to actually execute the
function’s code. This overhead occurs for small functions because the execution time
of a small function is less than the switching time.
2. It also saves the overhead of push/pop variables on the stack when a function
is called.
4. When you inline a function, you may enable the compiler to perform context-
specific optimization on the body of the function. Such optimizations are not
possible for normal function calls. Other optimizations can be obtained by
considering the flows of the calling context and the called context.
5. An inline function may be useful (if it is small) for embedded systems because
inline can yield less code than the function called preamble and return.
1. The added variables from the inlined function consume additional registers,
After the in-lining function if the variable number which is going to use the
register increases then they may create overhead on register variable
resource utilization. This means that when the inline function body is
substituted at the point of the function call, the total number of variables used
by the function also gets inserted. So the number of registers going to be
used for the variables will also get increased. So if after function inlining
variable numbers increase drastically then it would surely cause overhead on
register utilization.
2. If you use too many inline functions then the size of the binary executable file
will be large, because of the duplication of the same code.
3. Too much inlining can also reduce your instruction cache hit rate, thus
reducing the speed of instruction fetch from that of cache memory to that of
primary memory.
4. The inline function may increase compile time overhead if someone changes
the code inside the inline function then all the calling location has to be
recompiled because the compiler would be required to replace all the code
once again to reflect the changes, otherwise it will continue with old
functionality.
5. Inline functions may not be useful for many embedded systems. Because in
embedded systems code size is more important than speed.
6. Inline functions might cause thrashing because inlining might increase the
size of the binary executable file. Thrashing in memory causes the
performance of the computer to degrade. The following program
demonstrates the use of the inline function.
7. Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
Example:
#include <iostream>
int main()
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
Output