0% found this document useful (0 votes)
3 views

C++ base

The document provides an overview of C++ basic syntax, covering essential components such as header files, namespaces, main functions, and loops. It explains the structure of a C++ program, including the use of classes and decision-making statements like if, if-else, and switch statements. Additionally, it discusses different types of loops (for, while, and do-while) and their applications in programming.

Uploaded by

aravkr2007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C++ base

The document provides an overview of C++ basic syntax, covering essential components such as header files, namespaces, main functions, and loops. It explains the structure of a C++ program, including the use of classes and decision-making statements like if, if-else, and switch statements. Additionally, it discusses different types of loops (for, while, and do-while) and their applications in programming.

Uploaded by

aravkr2007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

C++ Basic Syntax

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.

Basic Syntax of a C++ Program

We can learn about basic C++ Syntax using the following program.

// C++ program to demonstrate the basic syntax

// Header File Library

#include <iostream>

// Standard Namespace

using namespace std;

// Main Function

int main()

// Body of the Function

// Declaration of Variable

int num1 = 24;

int num2 = 34;

int result = num1 + num2;

// Output

cout << result << endl;

// 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.

8. Basic Output cout


In line #7, we have used the cout stream object (declared in the <iostream> header file) to print the
sum of two numbers to the standard output stream (stdout).

Object-Oriented Programming in C++

C++ programming language supports both procedural-oriented and object-oriented programming.


The above example is based on the procedural-oriented programming paradigm. So let’s take
another example to discuss Object Oriented Programming in C++.

#include <iostream>

using namespace std;

class Calculate {

// Access Modifiers

public:

// data member

int num1 = 50;

int num2 = 30;

// member function

void addition() {

int result = num1 + num2;

cout << result << endl;

};

int main() {

// object declaration

Calculate add;

// member function calling

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.

2. Data Members & Member Functions

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>

using namespace std;

int main() {

// Print hello world 5 times

cout << "Hello World\n";


cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

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>

using namespace std;

int main() {

for (int i = 0; i < 5; i++) {

cout << "Hello World\n";

return 0;

Output

Hello World

Hello World

Hello World

Hello World
Hello World

What are Loops?

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.

C++ provides three loops:

Table of Content

 for Loop

 while Loop

 do while Loop

Let’s understand each of them in detail.

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

for (initialization; condition; updation) {


// body of for loop
}

The various parts of the for loop are:

 Initialization: Initialize the loop variable to some initial value.

 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>

using namespace std;


int main() {

// For loop that starts with i = 1 and ends

// when i is greater than 5.

for (int i = 1; i <= 5; i++) {

cout << i << " ";

return 0;

Output

12345

Important Properties of for Loop

 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.

Range Based for Loop

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>

using namespace std;

int main() {

vector<int> v { 1, 2, 3, 4, 5};

// Using range based for loop to print vector


for (auto i: v) {

cout << i << " ";

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
}

Only the condition is the part of while loop syntax, we have to do


the initialization and updation manually outside and inside the loop respectively.

Example

#include <iostream>

using namespace std;

int main() {

// Initialization

int i = 1;

// while loop that starts with i = 1 and ends

// when i is greater than 5.

while (i <= 5) {

cout << i << " ";


// Updation

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>

using namespace std;

int main() {

// Initialization

int i = 1;

// while loop that starts with i = 1 and ends

// when i is greater than 5.


do {

cout << i << " ";

// Updation

i++;

}while (i <= 5);

return 0;

Output

12345

Remember the last semicolon at the end of the loop.

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:

Using for Loop

#include <iostream>

using namespace std;

int main() {

// This is an infinite for loop as the condition

// expression is blank

for (;;) {

cout << "This loop will run forever.\n";

return 0;

Output
This loop will run forever.
This loop will run forever.
...................

Using while Loop

#include <iostream>

using namespace std;

int main() {

// This is an infinite while loop as the condition

// expression is always true

while(1) {

cout << "This loop will run forever.\n";

return 0;

Output

This loop will run forever.


This loop will run forever.
...................

Using do while Loop

#include <iostream>

using namespace std;

int main() {

// This is an infinite do while loop as the condition

// expression is always true

do {

cout << "This loop will run forever.\n";

}while(1);

return 0;
}

Output

This loop will run forever.


This loop will run forever.
...................

Decision Making in C++


Decision-making is the process to make a decision about which part of the code should be executed
or not based on some condition. Decision-making in C++ involves the usage of conditional
statements (also called decision control statements) to execute specific blocks of code primarily
based on given situations and their results.

Types of Decision-Making Statements in C++

In C++, the following decision-making statements are available:

 if in C++

 if-else in C++
 if-else if Ladder in C++

 Nested if-else in C++

 Switch Statement in C++

 Ternary Operator ( ? : ) in C++

 Jump Statements 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;

// Check if age is greater than 18 fo


// vote eligiblity
if (age > 18) {
cout << "allowed to vote";
}
return 0;
}

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;

// Using if-else to determine if the number is positive


// or non positive
if (n > 0) {
cout << "number is positive.";
}
else {
cout << "number is non-positive.";
}
return 0;
}

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

flow diagram of the if-else-if ladder


Example of if else Ladder
The below example demonstrates the use of an if-else-if ladder. In the
program, you are given an age and if the age is less the 13 print child, if the age
is between 13 to 18 print the growing stage, else print adult.
#include <iostream>
using namespace std;

int main() {
int age = 18;
// if this condition is true child is printed
if (age < 13) {
cout << "child";
}

// if above above if statement is not true then we check


// this else if condition if it evalutes to true print
// growing age
else if (age >= 1 and age <= 18) {
cout << "Growing stage";
}

// if none of above condition is true print adult


else {
cout << "adult";
}
return 0;
}

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

Flow diagram of Nested if-else


Example of Nested if else
The below example demonstrates the use of nested if-else. In the below
program, we are given a number and we have to check whether the number is
positive or negative or zero if the number is positive check whether it is even
or odd.
#include <iostream>
using namespace std;

int main() {
int n = 44;

// to check if n is positive
if (n > 0) {

// to check if the positive n is even or odd


if (n % 2 == 0) {
cout << "positive and even number";
}
else {
cout << "positive and odd number";
}
}
// to check if the n is 0
else if (n == 0) {
cout << "the number is zero";
}
// to check if the n is negative
else {
cout << "the number is negative";
}
return 0;
}

Output
positive and even number
5. Switch Statement

In C++, the switch statement is used when multiple situations need to be


evaluated primarily based on the value of a variable or an expression. switch
statement acts as an alternative to multiple if statements or if-else ladder and
has a cleaner structure and it is easy for handling multiple conditions.
Syntax of switch
switch (expression) {
case value_1:
// statements_break.
break;
case value_2:
// statements_2;
break;
…..
…..
default:
// default_statements;
break;
}
Flowchart of switch

Flowchart of switch in C++


Example of switch
The below example demonstrates the use of switches in decision-making. In
the below program, we are given a character and you have to give output as
per the given condition: if the given input is A then print GFG, and if the given
input is B print GeeksforGeeks else print invalid input.
#include <iostream>
using namespace std;

int main() {
char c = 'B';
switch (c) {

// if the input character is A then print GFG


case 'A':
cout << "GFG";
break;

// if the input character is B then print


// GeeksforGeeks
case 'B':
cout << "GeeksforGeeks";
break;
default:

// if the input character is invalid then print


// invalid input
cout << "invalid input";
}
return 0;
}

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;

// if the condition is true then num1 will be printed


// else num2 will printed
max = (num1 > num2) ? num1 : num2;
cout << max;
return 0;
}

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()
{

int age = 17;


if (age < 18) {
goto Noteligible;
}
else {
cout << "You can vote!";
}
Noteligible:
cout << "You are not eligible to vote!\n";
return 0;
}

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;

// Function to add two numbers and returns the result


int add(int a, int b)
{
int sum = a + b;
return sum; // Return the sum to the calling code
}

int main()
{
int res = add(3, 5);
cout << "The sum is: " << res << endl;

return 0;
}
Output
The sum is: 8

C++ Logical Operators

In C++ programming languages, logical operators are symbols that allow


you to combine or modify conditions to make logical evaluations. They
are used to perform logical operations on boolean values (true or false).

In C++, there are three logical operators:

 Logical AND Operator ( && )

 Logical OR Operator ( || )

 Logical NOT Operator ( ! )

1. Logical AND Operator ( && )


The C++ logical AND operator (&&) is a binary operator that returns true if
both of its operands are true. Otherwise, it returns false. Here’s the truth
table for the AND operator:
Operand 1 Operand 2 Result

true true true

true false false

false true false

false false False


Syntax

expression1 && expression2

Example

#include <iostream>

using namespace std;

int main() {

int age = 25;

bool isStudent = true;

// Using AND operator in if condition

if (age > 18 && isStudent) {

cout << "Student";

else {

cout << "Not Student";

return 0;
}

Output

Student

Explanation: In the above code, we have


used AND operator in the if condition to check whether
the age is greater than 18 and the person is a check. If
both conditions are true, the message “Student” will be
printed. Otherwise, the else statement is executed.

2. Logical OR Operator ( || )

The C++ logical OR operator ( || ) is a binary operator


that returns true if at least one of its operands is true. It
returns false only when both operands are false. Here’s
the truth table for the OR operator:

Operand 1 Operand 2 Result

true true true

true false true


Operand 1 Operand 2 Result

false true true

false false false

Syntax

expression1 || expression2

Example

#include <iostream>

using namespace std;

int main() {

int n = 7;

// using logical or for conditional statement

if (n <= 0 || n >= 10) {


cout << "n is not in range [0, 10]";

else {

cout << "n is in range [0, 10]";

return 0;

Output

n is in range [0, 10]

Explanation: In the above code, the condition num < 0 ||


num > 10 checks whether the number is either less than
equal to 0 or greater than equal to 10. If either of these
conditions is true, the message “The number is outside
the range of 0 to 10.” will be printed otherwise else
statement is printed.

3. Logical NOT Operator ( ! )

The C++ logical NOT operator ( ! ) is a unary operator


that is used to negate the value of a condition. It returns
true if the condition is false, and false if the condition is
true. Here’s the truth table for the NOT operator:

Operand 1 Result

true false

false true

Syntax

! expression

Example

#include <iostream>

using namespace std;

int main() {

bool isLoggedIn = false;

// using logical not operator


if (!isLoggedIn) {

cout << "Please log in.";

else {

cout << "Welcome to GeeksforGeeks!";

return 0;

Output

Please log in.

Explanation: In the above code, the


condition ‘!isLoggedIn’ checks whether the user is not
logged in. If the condition is true (i.e., the user is not
logged in), the message “Please log in to access this
feature.” will be displayed otherwise else statement will
be printed.
Enumeration in C++

Enumeration (Enumerated type) is a user-defined data type that can be assigned


some limited values. These values are defined by the programmer at the time of
declaring the enumerated type.

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

value1, value2, value3…..valueN

};

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.

enumerated-type-name variable-name = value;

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:

enum enumerated-type-name{value1=1, value2, value3};

Also, The consecutive values of the enum will have the next set of code value(s).
Example:

//first_enum is the enumerated-type-name

enum first_enum{value1=1, value2=10, value3};

In this case,

first_enum e;

e=value3;

cout<<e;

Output:

11

Example:

 C++

// C++ Program to Demonstrate the Functioning of Enumerators

// with an example of Gender

#include <bits/stdc++.h>

using namespace std;

int main()

// Defining enum Gender

enum Gender { Male, Female };

// Creating Gender type variable

Gender gender = Male;


switch (gender) {

case Male:

cout << "Gender is Male";

break;

case Female:

cout << "Gender is Female";

break;

default:

cout << "Value can be Male or Female";

return 0;

Output:

Gender is Male

// C++ Program to Demonstrate the Functioning of Enumerators

// with an Example of Year

#include <bits/stdc++.h>

using namespace std;

// Defining enum Year

enum year {

Jan,

Feb,

Mar,

Apr,

May,

Jun,

Jul,
Aug,

Sep,

Oct,

Nov,

Dec

};

// Driver Code

int main()

int i;

// Traversing the year enum

for (i = Jan; i <= Dec; i++)

cout << i << " ";

return 0;

Output:

0 1 2 3 4 5 6 7 8 9 10 11

C++ Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

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

 myFunction() is the name of the function

 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.

To call a function, write the function's name followed by two


parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action),


when it is called:

Example
Inside main, call myFunction():

// Create a function

void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"

A function can be called multiple times:

Example

void myFunction() {
cout << "I just got executed!\n";
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

Function Declaration and Definition

A C++ function consist of two parts:

 Declaration: the return type, the name of the function, and parameters (if
any)

 Definition: the body of the function (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}

Note: If a user-defined function, such as myFunction() is declared after


the main() function, an error will occur:

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();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// 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

void myFunction(string fname) {


cout << fname << " Refsnes\n";
}

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.

Parameter Passing Techniques in C++

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:

 Formal Parameters: Variables used in parameter list of a function as


placeholders. Also called only parameters.

 Actual Parameters: The expressions or values passed in during a function


call. Also called arguments.

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>

using namespace std;


// Arguments are pass by value

void change(int a) {

// Modifying arguments

a = 22;

int main() {

int x = 5;

// Passing x by value to change()

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

In pass-by-reference method, instead of passing the value of the argument, we pass


the reference of an argument to the function. This allows the function to change the
value of the original argument. This is useful when you have to pass large size data.

Example

#include <iostream>

using namespace std;


// Arguments are pass by value

void change(int& a) {

// Modifying arguments

a = 22;

int main() {

int x = 5;

// Passing x by reference to change()

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

The pass-by-pointer is very similar to the pass-by-reference method. The only


difference is that we pass the raw address of the argument as the parameter to the
function instead of reference.

Example

#include <iostream>

using namespace std;

// Arguments are pass by value


void change(int* a) {

// Modifying arguments

*a = 22;

int main() {

int x = 5;

// Passing address of x to change()

change(&x);

cout << x;

return 0;

Output

22

The original value is modified, but it increased to complexity of the program as we


need to be careful of referencing, referencing and passing addresses. So, passing
reference is preferred over this method.

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)

This example returns the sum of a function with two parameters:

int myFunction(int x, int y) {


return x + y;
}

int main() {
cout << myFunction(5, 3);
return 0;
}

// Outputs 8 (5 + 3)

You can also store the result in a variable:

Example

int myFunction(int x, int y) {


return x + y;
}

int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)

Function Overloading in C++

Function overloading is a feature of object-oriented programming where two or more


functions can have the same name but different parameters. When a function name
is overloaded with different jobs it is called Function Overloading. In Function
Overloading “Function” name should be the same and the arguments should be
different. Function overloading can be considered as an example of
a polymorphism feature in C++.
If multiple functions having same name but parameters of the functions should be
different is known as Function Overloading.
If we have to perform only one operation and having same name of the functions
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the function such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you to understand the
behavior of the function because its name differs.

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:

 Parameters should have a different type

add(int a, int b)
add(double a, double b)

Below is the implementation of the above discussion:

#include <iostream>

using namespace std;

void add(int a, int b)

cout << "sum = " << (a + b);

void add(double a, double b)

cout << endl << "sum = " << (a + b);

// Driver code
int main()

add(10, 2);

add(5.3, 6.2);

return 0;

Output

sum = 12

sum = 11.5

 Parameters should have a different number

add(int a, int b)
add(int a, int b, int c)

Below is the implementation of the above discussion:

#include <iostream>

using namespace std;

void add(int a, int b)

cout << "sum = " << (a + b);

void add(int a, int b, int c)

cout << endl << "sum = " << (a + b + c);

// Driver code
int main()

add(10, 2);

add(5, 6, 4);

return 0;

Output

sum = 12

sum = 15

 Parameters should have a different sequence of parameters.

add(int a, double b)
add(double a, int b)

Below is the implementation of the above discussion:

#include<iostream>

using namespace std;

void add(int a, double b)

cout<<"sum = "<<(a+b);

void add(double a, int 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

Following is a simple C++ example to demonstrate function overloading.

#include <iostream>

using namespace std;

void print(int i) {

cout << " Here is int " << i << endl;

void print(double f) {

cout << " Here is float " << f << endl;

void print(char const *c) {

cout << " Here is char* " << c << endl;

int main() {

print(10);

print(10.10);
print("ten");

return 0;

Output

Here is int 10

Here is float 10.1

Here is char* ten

#include<iostream>

using namespace std;

void add(int a, int b)

cout<<"sum ="<<(a+b);

void add(int a, int b,int c)

cout<<endl<<"sum ="<<(a+b+c);

main()

add(10,2);

add(5,6,4);

return 0;
}

#include<iostream>

using namespace std;

void add(int a, double b)

cout<<"sum ="<<(a+b);

void add(double a, int 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:

inline return-type function-name(parameters)


{
// function code
}
Remember, inlining is only a request to the compiler, not a command. The compiler
can ignore the request for inlining.

The compiler may not perform inlining in such circumstances as:

1. If a function contains a loop. (for, while and do-while)

2. If a function contains static variables.

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.

5. If a function contains a switch or goto statement.

Why Inline Functions are Used?

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.

Inline functions Advantages:

1. Function call overhead doesn’t occur.

2. It also saves the overhead of push/pop variables on the stack when a function
is called.

3. It also saves the overhead of a return call from a function.

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.

Inline function Disadvantages:

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>

using namespace std;

inline int cube(int s) { return s * s * s; }

int main()

cout << "The cube of 3 is: " << cube(3) << "\n";

return 0;

Output

The cube of 3 is: 27

You might also like