6. Functions in C ++ programming object oriented programmingAhmad177077
In C++, functions are used to organize code into modular blocks that can perform specific tasks. Functions allow you to avoid code repetition, improve code readability, and make your program more manageable.
The document discusses different types of storage classes in C++ that determine the lifetime and scope of variables:
1. Local variables are defined inside functions and have scope limited to that function. They are destroyed when the function exits.
2. Global variables are defined outside all functions and have scope in the entire program. They are destroyed when the program ends.
3. Static local variables are local variables that retain their value between function calls. Register variables are local variables stored in processor registers for faster access.
4. Thread local storage allows defining variables that are local to each thread and retain their values similar to static variables. The document provides examples to illustrate local, global, and static variables.
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
This document discusses functions in C programming. It begins by explaining why programs should be divided into smaller subprograms or functions for manageability. There are two types of functions: library functions which are pre-defined and cannot be modified, and user-defined functions which are created by the user. Every C program must contain a main() function. Functions allow code reusability and modularity. Parameters are used to pass data between functions. The return statement returns data from a function. Local variables are only accessible within their own function.
This document discusses functions in C++. It covers:
- The definition of a function as a subprogram that can act on data and return a value.
- Functions come in two varieties: user-defined and built-in.
- Functions must be declared before use with a prototype specifying the return type and parameters.
- A function is defined by providing the body of code that performs the task.
- Functions can interact through calls where parameters are passed by value or by reference.
The document discusses functions in C programming. It defines what a function is and explains the advantages of using functions, such as avoiding duplicate code and improving reusability. It describes the different parts of a function - declaration, definition, and call. It explains user-defined and standard library functions. It also covers parameter passing techniques (call by value and call by reference), recursion, and dynamic memory allocation using functions like malloc(), calloc(), realloc(), and free().
1) A function is a block of code that performs a specific task. Functions increase code reusability and improve readability.
2) There are two types of functions - predefined library functions and user-defined functions. User-defined functions are customized functions created by the user.
3) The main() function is where program execution begins. It can call other functions, which may themselves call additional functions. This creates a hierarchical relationship between calling and called functions.
Functions allow programmers to break programs into smaller, more manageable units called functions to make programs more modular and easier to write and debug; functions contain elements like a function prototype, parameters, definition, and body; and there are different types of functions like user-defined functions, library functions, and categories of functions based on whether they have arguments or return values.
The document discusses functions in C++. It defines functions as subprograms that can be compiled and tested separately, and reused in different programs. This modularization aids in managing large programs. Functions make programs easier to plan, code, test, debug, understand and maintain. Well-defined functions can be called from main() or from other functions. Parameters allow functions to access values from the calling context. Functions may return values to provide results. Functions increase code reuse and reduce duplication.
The document discusses user-defined functions in C programming. It covers topics like function declaration, definition, parameters, return values, function calls, categories of functions, recursion, scope and storage classes of variables in functions. Specifically, it defines a function, explains the need for user-defined functions, and describes the elements and different types of functions.
The document discusses functions in C programming. It defines a function as a block of code that performs a specific task. There are two types of functions: predefined standard library functions and user-defined functions. The key aspects of a function are its declaration, definition, and call. Functions can be used to break a large program into smaller, reusable components. Parameters can be passed to functions by value or by reference. Recursion is when a function calls itself, and is used in algorithms like calculating factorials. Dynamic memory allocation allows programs to request memory at runtime using functions like malloc(), calloc(), realloc(), and free().
The document discusses C++ functions. It defines what functions are and their uses in breaking down problems into smaller tasks. There are two types of functions: standard functions that are part of the C++ language and user-defined functions. A function has a signature defining its return type and parameters. Functions are declared and defined in two steps - declaration and implementation. Data can be shared between functions through parameters, which come in two varieties: value parameters that copy argument values, and reference parameters that can modify the original argument values.
The document discusses inline functions in C++. Inline functions allow code from a function to be pasted directly into the call site rather than executing a function call. This avoids overhead from calling and returning from functions. Good candidates for inline are small, simple functions called frequently. The document provides an example of a function defined with the inline keyword and the optimizations a compiler may perform after inlining. It also compares inline functions to macros and discusses where inline functions are best used.
Functions allow programmers to organize code into reusable blocks. A function is defined with a return type, name, parameters, and body. Functions can be called to execute their code from other parts of a program. Parameters allow data to be passed into functions, and functions can return data through return values or by reference. Inline functions avoid function call overhead by copying the function code into the calling location. Default parameters simplify function calls by automatically passing default values if arguments are omitted.
The document provides an overview of functions in C++. It discusses the basic concepts of functions including declaring, defining, and calling functions. It covers function components like parameters and arguments. It explains passing parameters by value and reference. It also discusses different types of functions like built-in functions, user-defined functions, and functions with default arguments. Additionally, it covers concepts like scope of variables, return statement, recursion, and automatic vs static variables. The document is intended to teach the fundamentals of functions as building blocks of C++ programs.
The document provides an overview of functions in C++. It discusses the basic concepts of functions including declaring, defining, and calling functions. It covers different types of functions such as built-in functions, user-defined functions, and functions that return values. The key components of a function like the prototype, definition, parameters, arguments, and return statement are explained. It also describes different ways of passing parameters to functions, including call by value and call by reference. Functions allow breaking down programs into smaller, reusable components, making the code more readable, maintainable and reducing errors.
The document discusses functions in C programming. It defines functions and explains their various parts like declaration, definition, and invocation. It also differentiates between function declaration and definition. Various types of functions are classified based on their inputs and outputs. The key differences between call by value and call by reference are explained with examples. Advantages of pass by reference are also mentioned.
The document discusses user-defined functions in C. It defines a user-defined function as a programmed routine with parameters set by the user. It covers the parts of a function including prototypes, calls, and definitions. It discusses passing parameters by value and reference. It also discusses local and global variables, recursion, and the advantages of user-defined functions in C.
This document discusses functions in Python. It defines what a function is and provides the basic syntax for defining a function using the def keyword. It also covers function parameters, including required, keyword, default, and variable-length arguments. The document explains how to call functions and discusses pass by reference vs pass by value. Additionally, it covers anonymous functions, function scope, and global vs local variables.
CJPCCS BCA VISNAGAR functions in C languageFCSCJCS
A function is a named, independent section of C code that performs a specific task. Functions allow programmers to break programs into smaller, reusable pieces of code. Functions may receive input parameters, perform some processing, and return an output value. When a function is called, its parameters are pushed onto the stack and the function code is executed. Upon returning, the stack frame is removed and the program counter returns to the calling location. Functions improve code organization and allow code reuse through modular programming.
Solidworks Crack 2025 latest new + license codeaneelaramzan63
Copy & Paste On Google >>> https://dr-up-community.info/
The two main methods for installing standalone licenses of SOLIDWORKS are clean installation and parallel installation (the process is different ...
Disable your internet connection to prevent the software from performing online checks during installation
Interactive Odoo Dashboard for various business needs can provide users with dynamic, visually appealing dashboards tailored to their specific requirements. such a module that could support multiple dashboards for different aspects of a business
✅Visit And Buy Now : https://bit.ly/3VojWza
✅This Interactive Odoo dashboard module allow user to create their own odoo interactive dashboards for various purpose.
App download now :
Odoo 18 : https://bit.ly/3VojWza
Odoo 17 : https://bit.ly/4h9Z47G
Odoo 16 : https://bit.ly/3FJTEA4
Odoo 15 : https://bit.ly/3W7tsEB
Odoo 14 : https://bit.ly/3BqZDHg
Odoo 13 : https://bit.ly/3uNMF2t
Try Our website appointment booking odoo app : https://bit.ly/3SvNvgU
👉Want a Demo ?📧 [email protected]
➡️Contact us for Odoo ERP Set up : 091066 49361
👉Explore more apps: https://bit.ly/3oFIOCF
👉Want to know more : 🌐 https://www.axistechnolabs.com/
#odoo #odoo18 #odoo17 #odoo16 #odoo15 #odooapps #dashboards #dashboardsoftware #odooerp #odooimplementation #odoodashboardapp #bestodoodashboard #dashboardapp #odoodashboard #dashboardmodule #interactivedashboard #bestdashboard #dashboard #odootag #odooservices #odoonewfeatures #newappfeatures #odoodashboardapp #dynamicdashboard #odooapp #odooappstore #TopOdooApps #odooapp #odooexperience #odoodevelopment #businessdashboard #allinonedashboard #odooproducts
Ad
More Related Content
Similar to Chapter 1 (2) array and structure r.pptx (20)
The document discusses functions in C programming. It defines what a function is and explains the advantages of using functions, such as avoiding duplicate code and improving reusability. It describes the different parts of a function - declaration, definition, and call. It explains user-defined and standard library functions. It also covers parameter passing techniques (call by value and call by reference), recursion, and dynamic memory allocation using functions like malloc(), calloc(), realloc(), and free().
1) A function is a block of code that performs a specific task. Functions increase code reusability and improve readability.
2) There are two types of functions - predefined library functions and user-defined functions. User-defined functions are customized functions created by the user.
3) The main() function is where program execution begins. It can call other functions, which may themselves call additional functions. This creates a hierarchical relationship between calling and called functions.
Functions allow programmers to break programs into smaller, more manageable units called functions to make programs more modular and easier to write and debug; functions contain elements like a function prototype, parameters, definition, and body; and there are different types of functions like user-defined functions, library functions, and categories of functions based on whether they have arguments or return values.
The document discusses functions in C++. It defines functions as subprograms that can be compiled and tested separately, and reused in different programs. This modularization aids in managing large programs. Functions make programs easier to plan, code, test, debug, understand and maintain. Well-defined functions can be called from main() or from other functions. Parameters allow functions to access values from the calling context. Functions may return values to provide results. Functions increase code reuse and reduce duplication.
The document discusses user-defined functions in C programming. It covers topics like function declaration, definition, parameters, return values, function calls, categories of functions, recursion, scope and storage classes of variables in functions. Specifically, it defines a function, explains the need for user-defined functions, and describes the elements and different types of functions.
The document discusses functions in C programming. It defines a function as a block of code that performs a specific task. There are two types of functions: predefined standard library functions and user-defined functions. The key aspects of a function are its declaration, definition, and call. Functions can be used to break a large program into smaller, reusable components. Parameters can be passed to functions by value or by reference. Recursion is when a function calls itself, and is used in algorithms like calculating factorials. Dynamic memory allocation allows programs to request memory at runtime using functions like malloc(), calloc(), realloc(), and free().
The document discusses C++ functions. It defines what functions are and their uses in breaking down problems into smaller tasks. There are two types of functions: standard functions that are part of the C++ language and user-defined functions. A function has a signature defining its return type and parameters. Functions are declared and defined in two steps - declaration and implementation. Data can be shared between functions through parameters, which come in two varieties: value parameters that copy argument values, and reference parameters that can modify the original argument values.
The document discusses inline functions in C++. Inline functions allow code from a function to be pasted directly into the call site rather than executing a function call. This avoids overhead from calling and returning from functions. Good candidates for inline are small, simple functions called frequently. The document provides an example of a function defined with the inline keyword and the optimizations a compiler may perform after inlining. It also compares inline functions to macros and discusses where inline functions are best used.
Functions allow programmers to organize code into reusable blocks. A function is defined with a return type, name, parameters, and body. Functions can be called to execute their code from other parts of a program. Parameters allow data to be passed into functions, and functions can return data through return values or by reference. Inline functions avoid function call overhead by copying the function code into the calling location. Default parameters simplify function calls by automatically passing default values if arguments are omitted.
The document provides an overview of functions in C++. It discusses the basic concepts of functions including declaring, defining, and calling functions. It covers function components like parameters and arguments. It explains passing parameters by value and reference. It also discusses different types of functions like built-in functions, user-defined functions, and functions with default arguments. Additionally, it covers concepts like scope of variables, return statement, recursion, and automatic vs static variables. The document is intended to teach the fundamentals of functions as building blocks of C++ programs.
The document provides an overview of functions in C++. It discusses the basic concepts of functions including declaring, defining, and calling functions. It covers different types of functions such as built-in functions, user-defined functions, and functions that return values. The key components of a function like the prototype, definition, parameters, arguments, and return statement are explained. It also describes different ways of passing parameters to functions, including call by value and call by reference. Functions allow breaking down programs into smaller, reusable components, making the code more readable, maintainable and reducing errors.
The document discusses functions in C programming. It defines functions and explains their various parts like declaration, definition, and invocation. It also differentiates between function declaration and definition. Various types of functions are classified based on their inputs and outputs. The key differences between call by value and call by reference are explained with examples. Advantages of pass by reference are also mentioned.
The document discusses user-defined functions in C. It defines a user-defined function as a programmed routine with parameters set by the user. It covers the parts of a function including prototypes, calls, and definitions. It discusses passing parameters by value and reference. It also discusses local and global variables, recursion, and the advantages of user-defined functions in C.
This document discusses functions in Python. It defines what a function is and provides the basic syntax for defining a function using the def keyword. It also covers function parameters, including required, keyword, default, and variable-length arguments. The document explains how to call functions and discusses pass by reference vs pass by value. Additionally, it covers anonymous functions, function scope, and global vs local variables.
CJPCCS BCA VISNAGAR functions in C languageFCSCJCS
A function is a named, independent section of C code that performs a specific task. Functions allow programmers to break programs into smaller, reusable pieces of code. Functions may receive input parameters, perform some processing, and return an output value. When a function is called, its parameters are pushed onto the stack and the function code is executed. Upon returning, the stack frame is removed and the program counter returns to the calling location. Functions improve code organization and allow code reuse through modular programming.
Solidworks Crack 2025 latest new + license codeaneelaramzan63
Copy & Paste On Google >>> https://dr-up-community.info/
The two main methods for installing standalone licenses of SOLIDWORKS are clean installation and parallel installation (the process is different ...
Disable your internet connection to prevent the software from performing online checks during installation
Interactive Odoo Dashboard for various business needs can provide users with dynamic, visually appealing dashboards tailored to their specific requirements. such a module that could support multiple dashboards for different aspects of a business
✅Visit And Buy Now : https://bit.ly/3VojWza
✅This Interactive Odoo dashboard module allow user to create their own odoo interactive dashboards for various purpose.
App download now :
Odoo 18 : https://bit.ly/3VojWza
Odoo 17 : https://bit.ly/4h9Z47G
Odoo 16 : https://bit.ly/3FJTEA4
Odoo 15 : https://bit.ly/3W7tsEB
Odoo 14 : https://bit.ly/3BqZDHg
Odoo 13 : https://bit.ly/3uNMF2t
Try Our website appointment booking odoo app : https://bit.ly/3SvNvgU
👉Want a Demo ?📧 [email protected]
➡️Contact us for Odoo ERP Set up : 091066 49361
👉Explore more apps: https://bit.ly/3oFIOCF
👉Want to know more : 🌐 https://www.axistechnolabs.com/
#odoo #odoo18 #odoo17 #odoo16 #odoo15 #odooapps #dashboards #dashboardsoftware #odooerp #odooimplementation #odoodashboardapp #bestodoodashboard #dashboardapp #odoodashboard #dashboardmodule #interactivedashboard #bestdashboard #dashboard #odootag #odooservices #odoonewfeatures #newappfeatures #odoodashboardapp #dynamicdashboard #odooapp #odooappstore #TopOdooApps #odooapp #odooexperience #odoodevelopment #businessdashboard #allinonedashboard #odooproducts
WinRAR Crack for Windows (100% Working 2025)sh607827
copy and past on google ➤ ➤➤ https://hdlicense.org/ddl/
WinRAR Crack Free Download is a powerful archive manager that provides full support for RAR and ZIP archives and decompresses CAB, ARJ, LZH, TAR, GZ, ACE, UUE, .
Landscape of Requirements Engineering for/by AI through Literature ReviewHironori Washizaki
Hironori Washizaki, "Landscape of Requirements Engineering for/by AI through Literature Review," RAISE 2025: Workshop on Requirements engineering for AI-powered SoftwarE, 2025.
AgentExchange is Salesforce’s latest innovation, expanding upon the foundation of AppExchange by offering a centralized marketplace for AI-powered digital labor. Designed for Agentblazers, developers, and Salesforce admins, this platform enables the rapid development and deployment of AI agents across industries.
Email: [email protected]
Phone: +1(630) 349 2411
Website: https://www.fexle.com/blogs/agentexchange-an-ultimate-guide-for-salesforce-consultants-businesses/?utm_source=slideshare&utm_medium=pptNg
Societal challenges of AI: biases, multilinguism and sustainabilityJordi Cabot
Towards a fairer, inclusive and sustainable AI that works for everybody.
Reviewing the state of the art on these challenges and what we're doing at LIST to test current LLMs and help you select the one that works best for you
Avast Premium Security Crack FREE Latest Version 2025mu394968
🌍📱👉COPY LINK & PASTE ON GOOGLE https://dr-kain-geera.info/👈🌍
Avast Premium Security is a paid subscription service that provides comprehensive online security and privacy protection for multiple devices. It includes features like antivirus, firewall, ransomware protection, and website scanning, all designed to safeguard against a wide range of online threats, according to Avast.
Key features of Avast Premium Security:
Antivirus: Protects against viruses, malware, and other malicious software, according to Avast.
Firewall: Controls network traffic and blocks unauthorized access to your devices, as noted by All About Cookies.
Ransomware protection: Helps prevent ransomware attacks, which can encrypt your files and hold them hostage.
Website scanning: Checks websites for malicious content before you visit them, according to Avast.
Email Guardian: Scans your emails for suspicious attachments and phishing attempts.
Multi-device protection: Covers up to 10 devices, including Windows, Mac, Android, and iOS, as stated by 2GO Software.
Privacy features: Helps protect your personal data and online privacy.
In essence, Avast Premium Security provides a robust suite of tools to keep your devices and online activity safe and secure, according to Avast.
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfTechSoup
In this webinar we will dive into the essentials of generative AI, address key AI concerns, and demonstrate how nonprofits can benefit from using Microsoft’s AI assistant, Copilot, to achieve their goals.
This event series to help nonprofits obtain Copilot skills is made possible by generous support from Microsoft.
What You’ll Learn in Part 2:
Explore real-world nonprofit use cases and success stories.
Participate in live demonstrations and a hands-on activity to see how you can use Microsoft 365 Copilot in your own work!
Download YouTube By Click 2025 Free Full Activatedsaniamalik72555
Copy & Past Link 👉👉
https://dr-up-community.info/
"YouTube by Click" likely refers to the ByClick Downloader software, a video downloading and conversion tool, specifically designed to download content from YouTube and other video platforms. It allows users to download YouTube videos for offline viewing and to convert them to different formats.
Who Watches the Watchmen (SciFiDevCon 2025)Allon Mureinik
Tests, especially unit tests, are the developers’ superheroes. They allow us to mess around with our code and keep us safe.
We often trust them with the safety of our codebase, but how do we know that we should? How do we know that this trust is well-deserved?
Enter mutation testing – by intentionally injecting harmful mutations into our code and seeing if they are caught by the tests, we can evaluate the quality of the safety net they provide. By watching the watchmen, we can make sure our tests really protect us, and we aren’t just green-washing our IDEs to a false sense of security.
Talk from SciFiDevCon 2025
https://www.scifidevcon.com/courses/2025-scifidevcon/contents/680efa43ae4f5
PDF Reader Pro Crack Latest Version FREE Download 2025mu394968
🌍📱👉COPY LINK & PASTE ON GOOGLE https://dr-kain-geera.info/👈🌍
PDF Reader Pro is a software application, often referred to as an AI-powered PDF editor and converter, designed for viewing, editing, annotating, and managing PDF files. It supports various PDF functionalities like merging, splitting, converting, and protecting PDFs. Additionally, it can handle tasks such as creating fillable forms, adding digital signatures, and performing optical character recognition (OCR).
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)Andre Hora
Software testing plays a crucial role in the contribution process of open-source projects. For example, contributions introducing new features are expected to include tests, and contributions with tests are more likely to be accepted. Although most real-world projects require contributors to write tests, the specific testing practices communicated to contributors remain unclear. In this paper, we present an empirical study to understand better how software testing is approached in contribution guidelines. We analyze the guidelines of 200 Python and JavaScript open-source software projects. We find that 78% of the projects include some form of test documentation for contributors. Test documentation is located in multiple sources, including CONTRIBUTING files (58%), external documentation (24%), and README files (8%). Furthermore, test documentation commonly explains how to run tests (83.5%), but less often provides guidance on how to write tests (37%). It frequently covers unit tests (71%), but rarely addresses integration (20.5%) and end-to-end tests (15.5%). Other key testing aspects are also less frequently discussed: test coverage (25.5%) and mocking (9.5%). We conclude by discussing implications and future research.
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDinusha Kumarasiri
AI is transforming APIs, enabling smarter automation, enhanced decision-making, and seamless integrations. This presentation explores key design principles for AI-infused APIs on Azure, covering performance optimization, security best practices, scalability strategies, and responsible AI governance. Learn how to leverage Azure API Management, machine learning models, and cloud-native architectures to build robust, efficient, and intelligent API solutions
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMaxim Salnikov
Imagine if apps could think, plan, and team up like humans. Welcome to the world of AI agents and agentic user interfaces (UI)! In this session, we'll explore how AI agents make decisions, collaborate with each other, and create more natural and powerful experiences for users.
Why Orangescrum Is a Game Changer for Construction Companies in 2025Orangescrum
Orangescrum revolutionizes construction project management in 2025 with real-time collaboration, resource planning, task tracking, and workflow automation, boosting efficiency, transparency, and on-time project delivery.
Not So Common Memory Leaks in Java WebinarTier1 app
This SlideShare presentation is from our May webinar, “Not So Common Memory Leaks & How to Fix Them?”, where we explored lesser-known memory leak patterns in Java applications. Unlike typical leaks, subtle issues such as thread local misuse, inner class references, uncached collections, and misbehaving frameworks often go undetected and gradually degrade performance. This deck provides in-depth insights into identifying these hidden leaks using advanced heap analysis and profiling techniques, along with real-world case studies and practical solutions. Ideal for developers and performance engineers aiming to deepen their understanding of Java memory management and improve application stability.
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?steaveroggers
Migrating from Lotus Notes to Outlook can be a complex and time-consuming task, especially when dealing with large volumes of NSF emails. This presentation provides a complete guide on how to batch export Lotus Notes NSF emails to Outlook PST format quickly and securely. It highlights the challenges of manual methods, the benefits of using an automated tool, and introduces eSoftTools NSF to PST Converter Software — a reliable solution designed to handle bulk email migrations efficiently. Learn about the software’s key features, step-by-step export process, system requirements, and how it ensures 100% data accuracy and folder structure preservation during migration. Make your email transition smoother, safer, and faster with the right approach.
Read More:- https://www.esofttools.com/nsf-to-pst-converter.html
F-Secure Freedome VPN 2025 Crack Plus Activation New Versionsaimabibi60507
Copy & Past Link 👉👉
https://dr-up-community.info/
F-Secure Freedome VPN is a virtual private network service developed by F-Secure, a Finnish cybersecurity company. It offers features such as Wi-Fi protection, IP address masking, browsing protection, and a kill switch to enhance online privacy and security .
2. 2
Objectives
After studying this chapter, students should be able to:
Learn about Introduction to function in C++
Learn about overview of component of function
Learn about overview of function calling
Learn about type of function
3. 3
Introduction to Function in C++
A program can be thought of as consisting of subparts, such as obtaining the input
data, calculating the output data, and displaying the output data.
C++, like most programming languages, has facilities to name and code each of these
subparts separately. In C++ these subparts are called functions.
Top-Down Design
A good plan of attack for designing the algorithm is to break down the task to be
accomplished into a few subtasks, decompose each of these subtasks into smaller
subtasks.
the subtasks become so small that they are trivial to implement in C++. This
method is called top-down design.
(The method is also sometimes called stepwise refinement, or more graphically,
divide and conquer.)
Using the top-down method, you design a program by breaking the program’s task into subtasks
and solving these subtasks by subalgorithms.
4. 4
Cont.
A function is a group of statements that together perform a task.
Every C++ program has at least one function, which is main, and all the most trivial
programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is so each
function performs a specific task.
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.
5. 5
Cont.
Built-in Functions
• C++ comes with libraries of predefined functions that you can use in your programs
• C++ language is shipped with a lot of functions which are known as standard functions
• These built-in functions are groups in different libraries which can be included in the C++
program, e.g.
• Math functions are declared in <math.h> library
• Character-manipulation functions are declared in <ctype.h> library
• C++ is shipped with more than 100 standard libraries, some of them are very popular such as
<iostream.h> and <stdlib.h>, others are very specific to certain hardware platform, e.g.
<limits.h> and <largeInt.h>
6. 6
Cont.
Input/Output Functions:
cin: Used for reading input from the user.
cout: Used for displaying output to the console.
getline: Reads a line of text from the input.
Mathematical Functions:
abs: Returns the absolute value of a number.
sqrt: Calculates the square root of a number.
pow: Raises a number to a specified power.
sin, cos, tan: Trigonometric functions.
String Functions:
strlen: Returns the length of a string.
strcpy, strncpy: Copies one string to another.
strcmp, strncmp: Compares two strings.
strcat, strncat: Concatenates strings.
Memory Functions:
• malloc, calloc: Allocate memory dynamically.
• free: Deallocates memory allocated dynamically.
• memcpy, memmove: Copies blocks of memory.
• memset: Sets blocks of memory with a specific value.
Conversion Functions:
• atoi, atol, atof: Converts a string to an integer, long, or
float, respectively.
• itoa, ltoa, ftoa: Converts an integer, long, or float to a
string, respectively.
Time Functions:
• time: Returns the current time as the number of seconds
since January 1, 1970.
• ctime: Converts a time value to a string representation.
• localtime, gmtime: Converts a time value to a structure
representing local time or UTC time.
7. 7
Cont.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "You entered: " << num << endl;
double squareRoot = sqrt(num);
cout << "Square root of " << num << "
is: " << squareRoot << endl;
return 0;
}
Function calling
the_root = sqrt(9.0);
function call
A function call is an expression consisting of the
function name followed by arguments enclosed in
parentheses. If there is more than one argument, the
arguments are separated by commas.
A function call is an expression that can be used like any other expression of the type specified for the value returned
by the function.
syntax
Function_Name(Argument_List) where the Argument_List is a comma-separated list of arguments:
Argument_1, Argument_2, . . . , Argument_Last
examples
side = sqrt(area);
cout << "2.5 to the power 3.0 is "
<< pow(2.5, 3.0);
8. 8
Cont.
#include <iostream>
#include <string>
using namespace std;
int main() {
string message = "Hello, World!";
int length = message.length();
cout << "Message: " << message << endl;
cout << "Length of the message: " << length <<
endl;
return 0;
}
boss to worker
A boss (the calling function or caller) asks a worker (the called function) to perform a task and return
(i.e., report back) the results when the task is done.
9. 9
User-Defined functions
Standard function may not be enough to
satisfy all users need
E.g, to find largest of two numbers
C++ provides its users with a way to define
their own functions
Structure of user-defined function
Function prototyping
Function definition
Functions are invoked by function call
Its where execution of the function begins
Function prototype
Tells compiler argument type and return type of
function
• Format for function prototyping
return-type function-name(argu-type1, argu-
type2, ...);
if function returns nothing, return type void
For example
int square(int);
Function takes an int and returns an int
int square(int a);
Optional to specify parameters’ names
10. 10
Function Definition
Format for function definition
return-value-type function-name(parameter-list)
{
… declarations and statements
}
Parameter-list (type par1, type par2, …)
Comma separated list of arguments
Data type needed for each argument
If no arguments, use void or leave blank
Return-value-type
Data type of result returned (use void if
nothing returned)
For example
int square(int y)
{
return y * y;
}
return keyword
Returns data, and control goes to function’s caller
Function prototype must match function definition
Function prototype
int maximum(int, int, int);
Function definition
int maximum(int x, int y, int z)
{
…
}
Functions cannot be defined inside other functions
11. 11
Function Calling
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
//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!"
12. 12
Cont.
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!
13. 13
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)
}
14. 14
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 << "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!";
}
15. 15
C++ Function Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside the
function.
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 functionName(parameter1, parameter2
, parameter3) {
// code to be 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:
16. 16
Cont.
Example
void myFunction(string fname) {
cout << fname << " Refsnesn";
}
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.
17. 17
C++ Default Parameters
Default Parameter Value
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 ("Norway"):
Example
void myFunction(string country
= "Norway") {
cout << country << "n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
A parameter with a default value, is often known as an "optional parameter".
From the example above, country is an optional parameter and "Norway" is the
default value.
18. 18
C++ Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
void myFunction(string
fname, int age) {
cout << fname << " Refsnes. " <<
age << " years old. n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
Note that when you are working with multiple parameters, the function call must have the
same number of arguments as there are parameters, and the arguments must be passed in
the same order.
19. 19
C++ The Return Keyword
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:
Example
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:
Example
int myFunction(int x, int y
) {
return x + y;
}
int main() {
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
20. 20
C++ Functions - Pass By Reference
In the examples from
the previous page, we
used normal variables
when we passed
parameters to a function.
You can also pass a
reference to the
function.
This can be useful when
you need to change the
value of the arguments:
Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "n";
cout << firstNum << secondNum << "n";
// Call the function, which will change the values of
firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "n";
cout << firstNum << secondNum << "n";
return 0;
}
21. 22
Example 2
//Function to add two numbers and return the sum
#include<iostream>
using namespace std;
#include<math.h>
int addition (int , int ); // function prototype
int main ( )
{
int a, b, c;
cout<<"Enter the value of a and b? ";
cin>>a>>b;
c = addition (a, b); // function calling
cout << "The sum is "<<c;
}
// function definition
int addition (int x, int y)
{
int z;
z= x + y;
return (z);
}
22. 23
Example 3
// Function to find the square of an integers between 1 and 10
#include<iostream>
using namespace std;
#include<math.h>
int square ( int ); // function prototype
int main ( )
{
for (int x = 1; x <= 10; x++)
cout<<square (x)<<" "; // function call
}
int square ( int y ) // function definition
{
return y * y;
}
23. 24
Cont.
Functions with empty parameter lists
void or leave parameter list empty
Indicates function takes no arguments
For example
void print(void); // or
Optional to specify void in the
parameter list
void print( );
Function print takes no arguments
and returns no value
// Function with void return type and
empty parameter list
#include<iostream>
using namespace std;
void printmessage ( ); // function
prototype
int main ( )
{
printmessage ( ); // function
calling
}
void printmessage ( ) // function
definition
{
cout << "I'm a function!";
}
24. 25
Example 5
//Function taking parameter list but with no
return type
#include<iostream>
using namespace std;
void addition (int , int ); // function prototype
int main ( )
{
int a, b, c;
cout<<"Enter the value of a and b? ";
cin>>a>>b;
addition (a, b); // function calling
}
// function definition
void addition (int x, int y)
{
int z;
z= x + y;
cout << "The sum is "<<z;
}
25. 26
Scope of Variables
The scope of a variable defines where it can be accessed/referenced in a
program
Local variables
All variables declared in the body of a function
Only accessed by the function declared it
All variables declared in main () are local variables
Global variables
Declared outside of all functions, before main ( )
Accessed by all functions, including main ( )
26. 27
Example 6
// local variables
#include<iostream>
using namespace std;
void update ( ); // function prototype
int main ( )
{
int x=5; // declare x local
variable to main ()
cout<<"The value of x local in
main () is: "<<x<<endl;
update ( ); // function
calling
cout<<"nThe value of x local
in main () is: "<<x<<endl;
update ( ); // function
calling
}
void update ( )
{
// x is not declared in
update (), can be accessed anywhere
cout <<"The value of x on
entering update () is: "<< x<<endl;
x = x*10;
cout <<"The value of x on
exiting update () is: "<< x<<endl;
}
27. 28
Example 7
// global variables
#include<iostream>
using namespace std;
void update ( ); // function prototype
int x=5; // declare x as global variable
int main ( )
{
// x is not declared in main
(), can be accessed anywhere
cout<<"The value of x in main
() is: "<<x;
update ( ); // function calling
cout<<"nThe value of x is:
"<<x;
}
// update ( ) modifies global variable x
during each call
void update ( )
{
// x is not declared in
update (), can be accessed anywhere
cout <<"The value of x on
entering update () is: "<< x<<endl;
x = x*10;
cout <<"The value of x on
exiting update () is: "<< x<<endl;
}
28. 29
Example 8
// local variable and global variable having the same name
#include<iostream>
void update ( ); // function prototype
int x=5; // declare x as global variable
int main ( )
{
update ( ); // function calling
}
void update ( )
{
int x=25; // declare x local variable to update ()
cout<<"The value of x is: "<<x<<endl;
}
29. 30
Scope Resolution Operator (: :)
• When global variable have same name with local variable in function
By default, local variable accessed in function
Unary scope resolution operator (::)
Access global variable in function, if local variable has same name
Format ::variable_name;
For example
Cout<<::x;
y = ::x + 3;
30. 31
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
31. 32
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 0
Global variables are automatically
initialized to 0
32. 33
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 0
void main()
{
x = 4;
fun();
cout << x << endl;
}
1
33. 34
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x ????
3
34. 35
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
3
35. 36
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
4
36. 37
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
5
37. 38
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
6
38. 39
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
7
39. 40
Example 9
// Using the unary scope resolution
operator
#include<iostream.h>
void update ( ); // function prototype
int x=1; // declare x as global
variable
int main ( )
{
int x=5; // declare x local
variable to main ()
cout<<“ The value of local x
is ”<<x;
cout<<“ The value of global x
is ”<<::x; // access global x in
main ()
//update ( ); // function
calling
void update ( )
{
int x=25; // declare x
local variable to update ()
cout<<“The value of local
x is ”<<x;
cout<<“The value of global
x is ”<<::x; // access global x in
update ()
}
40. 41
Storage Classes
Storage class determines the period during which a variable exists in
memory
Automatic variables
Variable created when program enters its block
Variable destroyed when program leaves block
For example
By default, local variables of functions
keyword auto explicitly declares automatic
auto int x;
Static variables
Created at which the program begins execution
Initialized once, when declared
Existed for the duration of the program execution
For example
By default, global variables are static
Local variables declared with keyword static
static int x=20;
Retains its value between function
calls
Reference to variable is local in the
function
41. 42
Passing Arguments to Function
There are two ways to pass arguments to function
Passing by value
Copies of argument value passed to function parameters
Changes made to the function parameters have no effect on the values of arguments
Prevent unwanted side effects
Passing by reference
Copies of argument address passed to function parameters
Any changes made to the function parameters affects or modify the values of arguments
42. 43
Example 1
// Passing arguments by value to function
#include<iostream>
using namespace std;
int squareByValue (int ); // function prototype
int main ( )
{
int x = 2;
cout<<"x before squareByValue (): "<<x<<endl;
cout<<"Value returned by squareByValue (): "<<squareByValue (x);
cout <<"nx after squareByValue (): "<<x;
}
int squareByValue( int number )
{
number = number * number;
return number;
}
43. 44
Cont’d…
There are two ways to pass arguments by
reference
Pass by reference with reference arguments
Pass by reference with pointer arguments
To pass by reference with reference arguments
Reference variable is used in function parameter
Alias for argument in function call
Passes parameter by reference
Use & after data type in prototype
void myFunction(int &data);
Read “data is a reference to an
int”
Function call format is the same
Reference variable
Alias for another variable
Contains the address of a variable (like a pointer)
A pointer constant, de-referenced
implicitly
Must be initialized when it is declared
Format to create a reference variable
type &reference-name =
referrer-name;
& indicates reference variable
Reference variable refer to variable of same type
Can be used within a function
44. 45
Cont’d…
For example
int x=5; //declare x as integer variable
int &y=x; //create y as an alias for x
cout<<x;
cout<<y;
Both output 5
int x=5;
int &y; // error
y=x;
Must be initialized when it is declared
45. 46
Example 2
// References must be initialized when declared
#include<iostream.h>
int main ( )
{
int x = 3;
int &y = x; // y refers to (is an alias for) x
cout<<"x = "<< x <<endl;
cout<<"y = "<< y <<endl;
y = 7;
cout<<"nx = "<<x<<endl;
cout<<"y = "<<y<<endl;
}
46. 47
Example 3
// Pass argument by reference with reference argument
#include<iostream>
using namespace std;
void squareByReference( int & ); // function prototype
int main ( )
{
int z = 4;
cout<<"z before squareByReference (): "<<z << endl;
squareByReference (z);
cout <<"z after squareByReference (): "<<z;
}
void squareByReference( int &numberRef )
{
numberRef = numberRef *numberRef;
}
47. 48
Cont’d…
To pass by reference with pointer arguments
Pointer variable is used in function parameter
Use * after data type in prototype
void myFunction(int *data);
& used to pass address of argument in fun. calling
myFunction(&value);
Arrays not passed with &
Because array name is already a pointer
48. 49
Example 4
// Pass argument by reference with pointer argument
#include<iostream.h>
void cubeByReference ( int * ); // function prototype
void main ( )
{
int number = 5;
cout<<"The original value of number is "<< number;
// pass address of number to cubeByReference
cubeByReference (&number );
cout << "nThe new value of number is " << number << endl;
}
void cubeByReference( int *nPtr )
{
*nPtr = *nPtr * *nPtr * *nPtr;
}
49. 50
Passing Array to Function
Specify name without brackets
To pass array myArray to myFunction
int myArray[24];
myFunction(myArray,24);
Array size usually passed, but not required
Useful to iterate over all elements
Arrays passed by reference
Functions can modify original array data
Value of name of array is address of first
element
Function knows where the array is
stored
Individual array elements passed by value
Like regular variables
square(myArray[3]);
Functions taking arrays
Function prototype for 1D array
void modifyArray(int [],
int);
No need for array size between brackets
Ignored by compiler
50. 51
Cont’d…
If declare array parameter as const
Cannot be modified (compiler error)
void doNotModify(const
int []);
Function prototypes for 2D arrays
Must specify sizes of subscripts
First subscript not necessary,
as with single-scripted arrays
void printArray(int[][3]);
//passing array to function
#include<iostream>
void printarray (int [ ], int ) ; // function prototype
void main ( )
{
int firstarray [ ] = {5, 10, 15};
int secondarray [ ] = {2, 4, 6, 8, 10};
printarray (firstarray, 3); // function
calling
printarray (secondarray, 5);
}
// function definition
void printarray (int array [ ], int size)
{
for (int i=0; i<size; i++)
cout<<array [i]<<" ";
cout << "n";
}
51. 52
Example 6
// Effects of passing entire array by reference
#include<iostream.h>
void modifyArray ( int [ ], int );
void main ( )
{
const int arraySize = 5;
int a [arraySize]= { 0, 1, 2, 3, 4 };
cout <<"Effects of passing entire array by
reference"<<endl;
cout<<"nThe values of a before modifyArray ():
";
// output original array
for (int i = 0; i < arraySize; i++ )
cout <<a[ i ]<<" ";
// pass array a to modifyArray by reference
modifyArray (a, arraySize );
cout<<"nnThe values of a after modifyArray (): ";
// output modified array
for ( int j = 0; j< arraySize; j++ )
cout<<a[j]<<" ";
}
// in function modifyArray, "b" points to the original array
"a" in memory
void modifyArray( int b[ ], int sizeOfArray)
{
for ( int k = 0; k < sizeOfArray; k++ )
b[k] = b[k] * 2;
}
52. 53
Example 7
// Effects of passing individual array element by
value
#include<iostream.h>
void modifyElement( int );
void main ( )
{
const int arraySize = 5;
int a [arraySize]= { 0, 1, 2, 3, 4 };
cout<<"Effects of passing individual array
element by value "<<endl;
cout<<"nThe value of a[3] before
modifyElement (): "<<a[3]<<endl;
// pass array element a[3] by value
modifyElement (a[3]);
// output value of a[ 3 ]
cout<<" nThe value of a[3] after modifyElement ():
"<<a[3];
}
// in function modifyElement, "e" is a local copy of array
element a[ 3 ] passed from main
void modifyElement( int e )
{
e = e * 2 ;
cout <<"nValue in modifyElement is: "<<e<<endl;
}
53. 54
Example 8
// passing multidimensional arrays to function by
reference
#include <iostream.h>
void printArray (int [ ] [3]); // function prototype
void main ( )
{
int array1 [2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2 [2][3] = { 1, 2, 3, 4, 5 };
cout<<"Values in array1 by row are:"<<endl;
printArray (array1);
cout<<"nValues in array2 by row are:"<<endl;
printArray (array2 );
}
// function to output array with two rows and three
columns
void printArray (int a[ ][3])
{
for (int i = 0; i < 2; i++ )
{
for (int j = 0; j < 3; j++ ) // output column
values
cout<<a[ i ][ j ]<<" ";
cout<<endl;
}
}
54. 55
Recursive Functions
Recursive functions
Functions that call themselves
Can only solve a base case
If not base case
Break problem into smaller problem(s)
Launch new copy of function to work on the smaller problem (recursive call/recursive step)
Slowly converges towards base case
Function makes call to itself inside the return statement
Eventually base case gets solved
Answer works way back up, solves entire problem
55. 56
Cont’d…
For example, factorial of an integer n
n! = n * (n – 1) * (n – 2) * … * 1
Recursive relationship, n! = n * (n – 1)!
5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1
Base case, 1! = 0! = 1
56. 57
Example 11
// Using recursive function to find the factorial of an
integer
#include<iostream.h>
long factorial ( long );
void main ( )
{
long number;
cout<<"Enter a number: ";
cin>>number;
cout<<number << "! = "<<factorial
(number);
}
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
57. 58
Inline Function
Each time a function called, the compiler must do the followings:
Remember where to return when the function eventually ends
Provide memory for the function’s variables
Provide memory for any value returned by the function
Pass control to from function calling to the function called
Pass control back to the calling function
This extra activity constitutes the overhead, or cost of doing business, involved in
calling a function
58. 59
Cont’d…
Inline function
Keyword inline before function
Asks the compiler to copy code into program instead of making function call
Appropriate argument substitutions made
Reduce function call overhead
Good for small, often-used functions
Appears prior to the main(), which calls it
Any inline function must precede any function that calls it, which eliminates the need
for prototyping in the calling function
For example
inline double cube(double s)
{
return s * s * s;
}
59. 60
Example 12
// Using inline function to calculate the volume of a cube
#include<iostream.h>
inline double cube (double side )
{
return (side * side * side);
}
void main ( )
{
double sideValue;
cout <<"Enter the side length of your cube: ";
cin>>sideValue;
cout <<"Volume of cube is "<<cube (sideValue );
}
60. 61
Overloaded Functions
Function overloading
Functions having same name, but with different
set of parameters (type, number, and order)
For example
Function to square ints and function to square
floats
int square(int x)
{
return x * x;
}
float square(float x)
{
return x * x;
}
• Compiler selects proper function to execute based
on number, types and order of arguments in the
function call.
• Commonly used to create several functions of the
same name that perform similar tasks, but on
different data types.
• Function can not be overloaded by its return type
61. 62
Example 12
// using overloaded functions
#include<iostream.h>
int square ( int x );
double square ( double y );
void main ( )
{
int x;
x= square (7); // calls int version of square
double y;
y = square(7.5 );
// calls double version of square
cout <<"nThe square of integer 7 is
"<<x<<endl;
cout<< "nThe square of double 7.5 is "<<y;
}
// function square for int values
int square ( int x )
{
cout <<"Called square with int argument:
"<<x<<endl;
return x * x;
}
// function square for double values
double square( double y )
{
cout <<"Called square with double
argument: "<<y <<endl;
return y * y;
}
62. 63
Building User-defined Libraries
• It is a good practice to group related functions into separate files, &
build your own libraries
W/c can be then included in many files
To build user-defined libraries,
How to create header files to store function prototype
How to create implementation files to store function definition, and link with the header file
How to include the header file to your program to use your user-defined functions
63. 64
How to Create Header Files
The C++ header files must have name with .h extension
Like string.h, math.h,… etc
The contents of header file should have ff structure:
#ifndef compiler directive
#define compiler directive
May include some other header files
All functions prototype with some comments
Definitions of data types and constants
#endif compiler directive
64. 65
Cont’d…
The header file is usually expected to reside in the same folder as the program file,
otherwise
A full or relative path to it should be specified
By default, all C++ standard header files are located in the C:TCWIN45INCLUDE
folder
To include header files in your program file
Standard library header files
#include<math.h>
User-defined header files
#include "myheader.h"
65. 66
Create taxrules.h Header File
#ifndef _TAXRULES_
#define _TAXRULES_
#include "taxrules.cpp"
double getIncome(char [ ]);
// purpose -- to get the employee income
// input -- a string prompt to be displayed to the user
// output -- a double value representing the income
66. 67
Cont’d…
double computeTaxes(double);
// purpose -- to compute the taxes for a given income
// input -- a double value representing the income
// output -- a double value representing the taxes
void printTaxes(double);
// purpose -- to display taxes to the user
// input -- a double value representing the taxes
// output -- None
#endif
68. 69
Include taxrules.h in Program File
#include<iostream.h>
#include "taxrules.h"
void main ( )
{
// get the income
double income;
income = getIncome ("Please enter the employee income: ");
// compute taxes
double taxes = computeTaxes(income);
// print employee taxes
printTaxes(taxes);
}
69. 70
Worksheet
What is the drawbacks of procedure-oriented programming?
Write a program that generate random number using rand()?
Write a program to find the Fibonacci Series of a given number using recursive
function?
Editor's Notes
#55: It is useful for many tasks, like sorting or calculate the factorial of numbers.