0% found this document useful (0 votes)
11 views50 pages

Understanding C++ Functions and Syntax

The document provides an overview of functions in C++, explaining their purpose, advantages, syntax, and types, including standard library functions and user-defined functions. It covers function declaration, definition, calling, parameters, arguments, default parameter values, return statements, and function overloading. Additionally, it categorizes user-defined functions based on their arguments and return values, emphasizing the importance of modularity and code reusability.

Uploaded by

mekashfetene89
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views50 pages

Understanding C++ Functions and Syntax

The document provides an overview of functions in C++, explaining their purpose, advantages, syntax, and types, including standard library functions and user-defined functions. It covers function declaration, definition, calling, parameters, arguments, default parameter values, return statements, and function overloading. Additionally, it categorizes user-defined functions based on their arguments and return values, emphasizing the importance of modularity and code reusability.

Uploaded by

mekashfetene89
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Introduction (Function)

 A function is a block of code that performs a specific task.

 Functions are used to provide modularity to a program.

 They allow complicated programs to be divided into manageable pieces.

 Dividing a complex problem into smaller chunks makes our program easy

to understand and reusable.


Introduction (Function)...cont’d
 Some advantages of functions:

− A programmer can focus on just that part of the program and construct
it, debug it, and perfect it
− Different people can work on different functions simultaneously
− Can be re-used (even in different programs)
− Enhance program readability.
Cont..
Syntax
void myFunction() {// code to be executed
}
 myFunction() is the name of the function

 Void: return type means that the function does not have a return value.
You will learn more about return values.
 parameters: are variables to hold values of arguments passed while
function is called. A function may or may not contain parameter list.
Introduction (Function)...cont’d
 There are two types of function:

 Standard Library Functions: Predefined in C++

 User-defined Function: Created by users


C++ Library Functions
 Library functions are the built-in functions in C++ programming.
 Programmers can use library functions by invoking the functions directly;
they don't need to write the functions themselves.
 Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
 In order to use library functions, we usually need to include the header file
in which these library functions are defined.
 For instance, in order to use mathematical functions such as sqrt() and
abs(), we need to include the header file cmath.
User-defined Function
 A user-defined function groups code to perform a specific task and
that group of code is given a name (identifier)
 When the function is invoked from any part of the program, it all
executes the codes defined in the body of the main function.
C++ 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

void myFunction() { // definition

// the body of the function (definition)

}
Cont..
 Note: If a user-defined function, such as myFunction() is declared
after the main() function, an error will occur:
 Example
int main() {
myFunction();
return 0;
}

void myFunction() {
cout << “Computer Science!";
}
// error
Function Prototype
Example:
 In C++, the code of function // function prototype
void add(int, int);
declaration should be before the int main() {
// calling the function
function call. before declaration
 However, if we want to define a add(5, 3);
return 0;
function after the function call, we }
// function definition
need to use the function [Link] add(int a, int b) {
cout << (a + b);
}
Function Prototype (...cont’d)
 In the above code, the function prototype is: void add(int, int);
 This provides the compiler with information about the function name and
its parameters. That's why we can use the code to call a function before
the function has been defined.
 The syntax of a function prototype is:
 returnType functionName(dataType1, dataType2, ...);
...cont’d
ExampleA: // function definition
void greet() {
cout << "Hello World";
}
Here, -- The name of the function is greet()
-- The return type of the function is void
-- The empty parentheses mean it doesn't have any parameters
-- The function body is written inside {........}
...cont’d
Benefits of Using User-Defined Functions
 Functions make the code reusable. We can declare them once and use
them multiple times.
 Functions make the program easier as each small task is divided into a
function.
 Functions increase readability.
Call 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:


Cont.…
// Create a function A function can be called multiple
void myFunction() { times:
cout << “Computer Science!"; void myFunction() {
}
cout << " Computer Science!\n";
int main() { }
myFunction(); // call the function
return 0; int main() {
} myFunction();
myFunction();
return 0;
}
Function Parameters and Argument
 The parameter is referred to as the variables that are defined during a function
declaration or definition.
 These variables are used to receive the arguments that are passed during a
function call.
 Parameters are specified after the function name, inside the parentheses.

 You can add as many parameters as you want, just separate them with a
comma(,):
 Syntax:void myfunction (parameter1, parameter2, parameter3) {
// code to be executed
Cont..
 Example : return a+b;
 Suppose a sum() function is needed to }
be called with two numbers to add
int main(){
 These two numbers are referred to as the
float num1=2.6,num2=8.8,result;
arguments and are passed to the sum()
when it called from somewhere else. result=sum(num1,num2);

#include<iostream> cout<<"the result of float is:\n"<<result;

using namespace std; return 0;

float sum(float a, float b){ }


cont..
 An argument is referred to the values that are passed within a function when
the function is called.
 These values are generally the source of the function that require the
arguments during the process of execution
 These values are assigned to the variables in the definition of the function that
is called.
 The type of the values passed in the function is the same as that of the
variables defined in the function definition. These are also called Actual
arguments or Actual Parameters.
Cont..
 Example: Suppose a Mult() function int main()
is needed to be defined to multiply {
two numbers.
int num1 = 8, num2 = 2, result;
#include <iostream>
// num1 & num2 as ARGUMENTS.
using namespace std;
result = Mult(num1, num2);
int Mult(int a, int b)
// a and b are the parameter
// Displaying the result
{
cout<<"the multiplication is\
return a * b; n"<<result;
// returning the multiplication return 0;
} }
Cont..
.
Example to declare and call function: (function with parameter)
// program to print a number
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1; Output:
cout << "The float number is " << n2; The int number is 5
}
The float number is 5.5
int main() {
int num1 = 5;
float num2 = 5.5;
// calling the function
displayNum(num1, num2);
return 0;
}
...cont’d
 In the above program, we have used a function that has one int
parameter and one double parameter.
 We then pass num1 and num2 as arguments. These values are stored by
the function parameters n1 and n2 respectively.
Note: The type of the
arguments passed
while calling the
function must match
with the
corresponding
parameters defined in
the function
declaration.
Default Parameter Value

A default argument is a value provided in a function declaration that is

automatically assigned by the compiler if the calling function doesn’t provide

a value for the argument. In case any value is passed, the default value is

overridden.

If the user does not supply a value, the default value will be used.

If the user supply a value to default parameter , the user value will be taken.
con..
#include<iostream>
using namespace std;
int mul(int a,int b, int c=0)
//assigning default values to c as 0
{
return (a*b*c);
}
int main(){
cout<<mul(10,2,7)<<endl;
cout<<mul(10,4,)<<endl;
return 0;
}
Cont..
You can also use a default parameter value, by using the equals sign (=).
If we call the function without an argument, it uses the default value
(“Ethiopia"):
 Example
void myFunction(string country = “Ethiopia") {
cout << country << "\n";
}

int main() {
myFunction(“Gambela");
myFunction(“Sidama");
myFunction(“Somale");
myfunction();
return 0; }
Default Arguments
(Parameters)...cont’d
Things to Remember:
All default parameter must be the right most parameter
Once we provide a default value for a parameter, all subsequent parameters
must also have default values. For example,
// Invalid
void add(int a, int b = 3, int c, int d);
// Invalid
void add(int a, int b = 3, int c, int d = 4);
// Valid void add(int a, int c, int b = 3, int d = 4);
Return Statement
 Return statement is used when we need to specify the return
Type of the function during function declaration.
 Then, the return statement can be used to return a value from a
function.
• Example:
int add (int a, int b) {
return (a + b);
}
 We have the data type int instead of void. This means that the
function returns an int value.
Return Statement (...cont’d)
 The code return (a + b); returns the sum of the two parameters as the function
value.
 The return statement denotes that the function has ended. Any code after
return inside the function is not executed.
Notice that sum
is a variable of
int type. This is
because the
return value of
add() is of int
type.
Cont..
#include<iostream>
using namespace std;
int sum(int a, int b){
return a+b;
}
int main(){
int add;
add=sum(2,5);
cout<<add;

return 0;
}
Cont..
#include<iostream>
using namespace std;
int myFunction(int x,int y) {
return x*y;
}
int main() {
cout << myFunction(3,7);
return 0;
}
C++ Function Overloading
 In C++, two functions can have the same name if the number and/or type
of arguments passed is different.
 These functions having the same name but different arguments are known
as overloaded functions.
For example:
// same function name with different arguments
− int test() { }
− int test(int a) { }
− float test(double a) { }
− int test(int a, double b) { }
C++ Function Overloading(...cont’d)
 On the above example, all 4 functions are overloaded functions.
Notice:
 The return types of all these 4 functions are not the same.
 Overloaded functions may or may not have different return types but they
must have different arguments.
For example, // Error code
int test(int a) { }
double test(int b){ }
 Here, both functions have the same name, the same type, and the same
number of arguments. Hence, the compiler will throw an error.
Cont..
#include <iostream> int main()
using namespace std; {
void add(double a, double b) add(19, 12);
{ add(9.5, 3.4);
cout << endl << "sum = " << (a + b); return 0;
} }
void add(int a, int b)
{
cout << "sum = " << (a + b);
}
C++ Function Overloading(...cont’d)
Overloading Using Different Types of Parameter
C++ Function Overloading(...cont’d)
Overloading Using Different Number of
Parameter
Note: In C++, many standard
library functions are overloaded.
For example, the sqrt() function
can take double, float, int, etc. as
parameters.
 This is possible because the
sqrt() function is overloaded
in C++.
Function (...cont’d)
User Defined Function

 There are different approaches you can take to solve a single problem using
functions
 For better understanding of arguments and return in functions, user-defined
functions can be categorised as:
 Function with no argument and no return value
 Function with no argument but return value
 Function with argument but no return value
 Function with argument and return value
[Link] with no argument and no return value
Example-1:  In the above program, prime() is
# include <iostream>
called from the main() with no
using namespace std; arguments.
void prime();  prime() takes the positive number
int main() { from the user and checks whether
// No argument is passed to prime()
the number is a prime number or
prime();
not.
return 0;  Since, return type of prime() is
}
// Return type of function is void because value is not
void, no value is returned from the
returned. function.
void prime()
{
...statements
}
Function with no argument but a
return
Example-2: No arguments passed but
return value
a value
 In the above program, prime()
#include <iostream>
using namespace std; function is called from the main()
int prime(); with no arguments.
int main()  prime() takes a positive integer from
{
// No argument is passed to prime()
the user. Since, return type of the
num = prime(); function is an int, it returns the
return 0; inputted number from the user back
} to the calling main() function.
// Return type of function is int  Then, whether the number is prime
int prime() {
int n; or not is checked in the main()
cout<<"enter any number ") itself and printed onto the
cin >> n; screen.
return n; }
Function with argument and no return
value
Example-3: Arguments passed but no return value
void prime(int n) {
#include <iostream>
using namespace std; .....
void prime(int n); }
int main() {  In the above program, positive number is
int num; first asked from the user which is stored
cout << "Enter a positive integer to check: "; in the variable num.
cin >> num;  Then, num is passed to the prime()
// Argument num is passed to the function prime() function where, whether the number is
prime(num);
prime or not is checked and printed.
return 0;
}
/* There is no return value to calling function.  Since, the return type of prime() is a void,
Hence, return type of function is void. */ no value is returned from the function.
Function with argument and return value
Example-4: Arguments passed and return  In the above program, a positive integer is
value asked from the user and stored in the variable
#include <iostream> num.
using namespace std;  Then, num is passed to the function prime()
int prime(int n);
where, whether the number is prime or not is
int main() {
int num;
checked.
cout << "Enter positive integer to check:";
 Since, the return type of prime() is an int, 1 or
cin >> num; 0 is returned to the main() calling function. If
return 0; the number is a prime number, 1 is returned.
} If not, 0 is returned.
// This function returns integer value  Back in the main() function, the returned 1 or
int prime(int n) { 0 is stored in the variable created to hold it,
...statements; and the corresponding text is printed onto the
return statement; screen.
}
C++ Storage Class
• Every variable in C++ has two features: type and storage class.
• Type specifies the type of data that can be stored in a variable. For
example: int, float, char etc.
• Storage class controls two different properties of a variable:
• lifetime (determines how long a variable can exist) and
• scope (determines which part of the program can access it).
• Depending upon the storage class of a variable, it can be divided into the
following types:
• Local variable
• Global variable
• Static local variable
• Register Variable
• Thread Local Storage
C++ Storage Class(...cont’d)
Local Variable

• A variable defined inside a function (defined inside function body

between braces) is called a local variable or automatic variable.

• Its scope is only limited to the function where it is defined. In simple

terms, local variable exists and can be accessed only inside a function.

• The life of a local variable ends (It is destroyed) when the function exits.
C++ Storage Class(...cont’d)
Global Variable

• If a variable is defined outside all functions, then it is called a global

variable.

• The scope of a global variable is the whole program. This means, It can

be used and changed at any part of the program after its declaration.

• Likewise, its life ends only when the program ends.


C++ Storage Class(...cont’d)
Static Local variable

• Keyword static is used for specifying a static variable.

• A static local variable exists only inside a function where it is declared

(similar to a local variable), but its lifetime starts when the function is

called and ends only when the program ends.

• The main difference between local variable and static variable is that, the

value of static variable persists the end of the program.


C++ Storage Class(...cont’d)
Register Variable

• Keyword register is used for specifying register variables.

• Register variables are similar to automatic variables and exists inside a

particular function only.

• It is supposed to be faster than the local variables.

• If a program encounters a register variable, it stores the variable in

processor's register rather than memory if available. This makes it faster


C++ Storage Class(...cont’d)
Thread Local Storage

• Thread-local storage is a mechanism by which variables are allocated

such that there is one instance of the variable per extant thread.

• Keyword thread_local is used for this purpose.


C++ Storage Class Example
#include <iostream>
using namespace std;
// Global variable (c) declaration void test()
int c = 12; {
void test(); // local variable (var1) to
int main() test()
{ int var1;
// local variable (var) to main() var1 = 6;
int var = 5;
test(); // illegal: var not declared
// illegal: var1 not declared inside inside test()
main() cout << var;
var1 = 9; /* Outputs 12 b/c of c is
// static local variable (var2) global variable */
cout << c;
C++ Recursion
 A function that calls itself is known as a recursive function. And, this
technique is known as recursion.
C++ Recursion(...cnt’d)
• The recursion continues until some condition is met.
• To prevent infinite recursion, if...else statement or similar approach can
be used where one branch makes the recursive call and the other doesn't.
Example:
int factorial(int n)
{
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
C++ Recursion(...cnt’d)
 Advantages of C++ Recursion

 It makes our code shorter and cleaner.

 Recursion is required in problems concerning data structures and

advanced algorithms, such as Graph and Tree Traversal.

 Disadvantages of C++ Recursion

 It takes a lot of stack space compared to an iterative program.

 It uses more processor time.


C++ Return by Reference
• In C++ Programming, not only can you pass values by reference
to a function but you can also return a value by reference.
#include <iostream> // function definition
using namespace std; // returns the address of num
// global variable variable
int num; int& test() {
// function prototype return num;
int& test(); }
int main() {
// assign 5 to num variable
// equivalent to num = 5;
test() = 5;
cout << num; Output
return 0; 5
}

You might also like