It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
Create the equivalent of a four function calculator. The program should request the user to enter a number, an operator, and another number. carry out the specified arithmetical operation: adding, subtracting, multiplying, or dividing the two numbers. (Using switch statement ).ThesisScientist.com
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docxeugeniadean34240
20145-5SumII_CSC407_assign1.html
CSC 407: Computer Systems II: 2015 Summer II, Assignment #1
Last Modified 2015 July 21Purpose:
To go over issues related to how the compiler and the linker
serve you, the programmer.
Computing
Please ssh into ctilinux1.cstcis.cti.depaul.edu, or use your own Linux machine.
Compiler optimization (45 Points)
Consider the following program.
/* q1.c
*/
#include <stdlib.h>
#include <stdio.h>
#define unsigned int uint
#define LENGTH ((uint) 512*64)
int initializeArray (uint len,
int* intArray
)
{
uint i;
for (i = 0; i < len; i++)
intArray[i] = (rand() % 64);
}
uint countAdjacent (int maxIndex,
int* intArray,
int direction
)
{
uint i;
uint sum = 0;
for (i = 0; i < maxIndex; i++)
if ( ( intArray[i] == (intArray[i+1] + direction) ) &&
( intArray[i] == (intArray[i+2] + 2*direction) )
)
sum++;
return(sum);
}
uint funkyFunction (uint len,
int* intArray
)
{
uint i;
uint sum = 0;
for (i = 0; i < len-1; i++)
if ( (i % 8) == 0x3 )
sum += 7*countAdjacent(len-2,intArray,+1);
else
sum += 17*countAdjacent(len-2,intArray,-1);
return(sum);
}
int main ()
{
int* intArray = (int*)calloc(LENGTH,sizeof(int));
initializeArray(LENGTH,intArray);
printf("funkyFunction() == %d\n",funkyFunction(LENGTH,intArray));
free(intArray);
return(EXIT_SUCCESS);
}
(8 Points) Compile it for profiling but with no extra optimization with:
$ gcc -o q1None -pg q1.c # Compiles q1.c to write q1None to make profile info
$ ./q1None # Runs q1None
$ gprof q1None # Gives profile info on q1None
Be sure to scroll all the way to the top of gprof output!
What are the number of self seconds taken by:
FunctionSelf secondsinitializeBigArray()__________countAdjaceent()__________funkyFunction()__________
(8 Points)
How did it do the operation (i % 8) == 0x3?
Was it done as a modulus (the same as an expensive division, but returns the remainder instead of the quotient) or something else?
Show the assembly language for this C code
using gdb to dissassemble
funkyFunction() of q1None.
Hint: do:
$ gdb q1None
. . .
(gdb) disass funkyFunction
Dump of assembler code for function funkyFunction:
. . .
and then look for the code that sets up the calls to countAdjacent().
The (i % 8) == 0x3 test is done before either countAdjacent() call.
(8 Points) Compile it for profiling but with optimization with:
$ gcc -o q1Compiler -O1 -pg q1.c # Compiles q1.c to write q1Compiler to make profile info
$ ./q1Compiler # Runs q1Compiler
$ gprof q1Compiler # Gives profile info on q1Compiler
What are the number of self seconds taken by:
FunctionSelf secondsinitializeBigArray()__________countAdjacent()__________funkyFunction()__________(8 Points) Use gdb to dissassemble countAdjacent() of both q1None and q1.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
Create the equivalent of a four function calculator. The program should request the user to enter a number, an operator, and another number. carry out the specified arithmetical operation: adding, subtracting, multiplying, or dividing the two numbers. (Using switch statement ).ThesisScientist.com
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docxeugeniadean34240
20145-5SumII_CSC407_assign1.html
CSC 407: Computer Systems II: 2015 Summer II, Assignment #1
Last Modified 2015 July 21Purpose:
To go over issues related to how the compiler and the linker
serve you, the programmer.
Computing
Please ssh into ctilinux1.cstcis.cti.depaul.edu, or use your own Linux machine.
Compiler optimization (45 Points)
Consider the following program.
/* q1.c
*/
#include <stdlib.h>
#include <stdio.h>
#define unsigned int uint
#define LENGTH ((uint) 512*64)
int initializeArray (uint len,
int* intArray
)
{
uint i;
for (i = 0; i < len; i++)
intArray[i] = (rand() % 64);
}
uint countAdjacent (int maxIndex,
int* intArray,
int direction
)
{
uint i;
uint sum = 0;
for (i = 0; i < maxIndex; i++)
if ( ( intArray[i] == (intArray[i+1] + direction) ) &&
( intArray[i] == (intArray[i+2] + 2*direction) )
)
sum++;
return(sum);
}
uint funkyFunction (uint len,
int* intArray
)
{
uint i;
uint sum = 0;
for (i = 0; i < len-1; i++)
if ( (i % 8) == 0x3 )
sum += 7*countAdjacent(len-2,intArray,+1);
else
sum += 17*countAdjacent(len-2,intArray,-1);
return(sum);
}
int main ()
{
int* intArray = (int*)calloc(LENGTH,sizeof(int));
initializeArray(LENGTH,intArray);
printf("funkyFunction() == %d\n",funkyFunction(LENGTH,intArray));
free(intArray);
return(EXIT_SUCCESS);
}
(8 Points) Compile it for profiling but with no extra optimization with:
$ gcc -o q1None -pg q1.c # Compiles q1.c to write q1None to make profile info
$ ./q1None # Runs q1None
$ gprof q1None # Gives profile info on q1None
Be sure to scroll all the way to the top of gprof output!
What are the number of self seconds taken by:
FunctionSelf secondsinitializeBigArray()__________countAdjaceent()__________funkyFunction()__________
(8 Points)
How did it do the operation (i % 8) == 0x3?
Was it done as a modulus (the same as an expensive division, but returns the remainder instead of the quotient) or something else?
Show the assembly language for this C code
using gdb to dissassemble
funkyFunction() of q1None.
Hint: do:
$ gdb q1None
. . .
(gdb) disass funkyFunction
Dump of assembler code for function funkyFunction:
. . .
and then look for the code that sets up the calls to countAdjacent().
The (i % 8) == 0x3 test is done before either countAdjacent() call.
(8 Points) Compile it for profiling but with optimization with:
$ gcc -o q1Compiler -O1 -pg q1.c # Compiles q1.c to write q1Compiler to make profile info
$ ./q1Compiler # Runs q1Compiler
$ gprof q1Compiler # Gives profile info on q1Compiler
What are the number of self seconds taken by:
FunctionSelf secondsinitializeBigArray()__________countAdjacent()__________funkyFunction()__________(8 Points) Use gdb to dissassemble countAdjacent() of both q1None and q1.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
2. Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
void SquareArea()
{
double Side;
cout << "nEnter the side of the square: ";
cin >> Side;
cout << "nSquare characteristics:";
cout << "nSide = " << Side;
cout << "nArea = " << Side * Side << endl;;
}
int main(void)
{
SquareArea();
system("PAUSE");
return 0;
}
Enter the side of the square: 5
Square characteristics:
Side = 5
Area = 25
Press any key to continue . . .
Function with no return value and no parameters
Standard Name Space
Function Heading
Function Body
Function Call
Output
3. Computer Programming II
Techniques of Returning a Value
void Functions: A function that does
not return a value is declared and defined
as void.
#include <iostream>
#include <cstdlib>
using namespace std;
void Hello(void)
{
cout << "------------------------n"
<< "| Hello |n"
<< "-------------------------n" ;
}
int main(void)
{
Hello();
system("PAUSE");
return 0;
}
----------------------
| Hello |
--------------------------
Press any key to continue . . .
Returning a Value: If you declare a function
that is returning anything (a function that is not void),
the compiler will need to know what value the function
returns. The return value must be the same type
declared. The value is set with the return keyword.
char Answer()
{
char a;
cout << “Quit (y=Yes/n=No)? ";
cin >> a;
return a;
}
double SquareArea (double Side)
{
return (Side * Side);
}
double SquareArea(double Side)
{
double Area;
Area = Side * Side;
return Area;
}
4. Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
int GetMajor(void)
{
int Choice;
cout << "n1 - Business Administration";
cout << "n2 - History";
cout << "n3 - Geography";
cout << "n4 - Education";
cout << "n5 - Computer Sciences";
cout << "nYour Choice: ";
cin >> Choice;
return Choice;
}
int main(void)
{
int Major;
cout << "Welcome to the student orientation program.";
cout << "Select your desired major:";
Major = GetMajor();
cout << "You select " << Major;
cout << "n";
system("PAUSE");
return 0;
}
Call GetMajor and
when done return the
results to the variable
Major
Return Value but no
Parameters
#include <iostream>
using namespace std;
double TotPrice(double ItemPrice, double TaxRate)
{
double Price;
Price = ItemPrice + (ItemPrice * TaxRate / 100);
return Price;
}
int main()
{
double ItemPrice, TaxRate;
cout << "Enter the price of the item: ";
cin >> ItemPrice;
cout << "Enter the tax rate: ";
cin >> TaxRate;
cout << "nThe final price is: "
<< TotPrice(ItemPrice, TaxRate);
cout << "nn";
return 0;
}
Enter the price of the item: 125.95
Enter the tax rate: 5.75
The final price is: 133.19
6. Computer Programming II
References in Functions
• Recall that the two primary motivations
for using references are related to their
use in functions:
– References are cleaner, and less error-
prone than pointers, especially when used
in functions
– Using references instead of pointers in
function prototypes will make their use
transparent to the calling program
7. Computer Programming II
Pass-By-Reference
• As an example, consider a function for
swapping the values contained in two integer
variables:
void swap (int* x, int* y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void swap (int& x, int& y)
{
int temp;
temp = x;
x = y;
y = temp;
}
Using Pointers Using References
8. Computer Programming II
Pass-By-Reference
• However, the simplicity of references is realized not
only in a function’s implementation, but also in its use:
Using Pointers Using References
int var1 = 10;
int var2 = 20;
swap (&var1, &var2);
int var1 = 10;
int var2 = 20;
swap (var1, var2);
• The use of references is transparent to the user!
9. Computer Programming II
Pass-By-Reference
• A nice side effect of the requirement that references
be initialized is that it removes the need to check for
null values in function calls
void myFunction(int* x) {…} // Must check that x != null
void myFunction(int& x) {…} // x cannot be null
10. Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int &x, int &y);
int main()
{
int x=6, y=9;
cout << "Before the swap:n";
cout << "X: " << x << endl;
cout << "Y: " << y << endl;
swap(x, y);
cout << "nAfter the swap:n";
cout << "X: " << x << endl;
cout << "Y: " << y << endl;
system("PAUSE");
return 0;
}
void swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
Before the swap:
X: 6
Y: 9
After the swap:
X: 9
Y: 6
Press any key to continue . . .
11. Computer Programming II
#include <iostream>
#include <string>
using namespace std;
void change(int& a)
{
a = 33;
cout << "n2:" << a ;
}
void main()
{
int x = 100;
cout << "n1:" << x ;
change(x);
cout << "n3:" << x ;
}
1:100
2:33
3:33
#include <iostream>
#include <string>
using namespace std;
void change(int* a)
{
*a = 33;
cout << "n2:" << *a ;
}
void main()
{
int x = 100;
cout << "n1:" << x ;
change(&x);
cout << "n3:" << x ;
}
Using Reference Using Pointer
12. Computer Programming II
Pass-By-Const-Reference
• One advantage of pass-by-value is that it prevents a
function from altering the original arguments (since it
operates on copies of those arguments)
• However, we have already pointed out that creating a
copy of a large object can be very time-consuming
• C++ allows us to get the best of both worlds, by using
pass-by-const-reference
int myFunction(const int& x);
13. Computer Programming II
Pass-By-Const-Reference
• Using pass-by-const-reference provides both
the speed advantage of pass-by-reference and
the safety of pass-by-value
• Of course, this is not something that a user can
affect, so it is up to you to see if a function you
will be using has pass-by-const-reference
• Instead, this is really away that you, as a
programmer, can be sure that you don’t
inadvertently alter input parameters and
advertise that fact to users
14. Computer Programming II
#include <iostream.h>
#include <stdlib.h>
using namespace std;
int main()
{
double price, PriceAfterDiscount;
double computeDiscountedPrice (const double &price);
cout << "enter the price of the item";
cin >> price;
PriceAfterDiscount = computeDiscountedPrice(price);
cout << "the original price is $" << price << endl;
cout << "The final price after discount is $"
<< PriceAfterDiscount << endl;
system("PAUSE");
return 0;
}
double computeDiscountedPrice (const double &price)
{
double newPrice;
if (price > 100.0)
newPrice = price * .80;
else
newPrice = price * .90;
return newPrice;
}
enter the price of the item180
the original price is $180
The final price after discount is $144
Press any key to continue . . .
15. Computer Programming II
Returning References
• As with other data types, we can return a
reference from a function
int& myFunction() {…}
• When choosing to return a reference, it is
imperative to remember the C++ scope rules
• The object to which the reference refers to had
better exist after the function exits
16. Computer Programming II
Returning References
• There are two primary ways that references are safely
returned
• Return a reference to an object that was passed into
the function
int& pickANumber(int& a, int& b, int& c);
• Return a reference to an object that was dynamically
allocated within the function using new
• An interesting side effect of returning references is
that we can use the assignment operator with
functions:
int& myFunction() {…}
myFunction() = 5; // This is a valid statement!
17. Computer Programming II
#include <iostream.h>
#include <stdlib.h>
const int SIZE = 6;
int &put_val(int a[], int n)
{
if (n >= SIZE || n < 0)
{
cout << " Out side of boundaries";
exit(1);
}
return a[n];
}
int main()
{
int Arr[SIZE];
for (int i=0;i<SIZE;i++)
put_val(Arr,i) = i*2;
for (int j=0;j<SIZE;j++)
cout << "Arr["<<j<<"]="<<Arr[j] <<endl;
system("PAUSE");
return 0;
}
Function call is on the left
Arr[0]=0
Arr[1]=2
Arr[2]=4
Arr[3]=6
Arr[4]=8
Arr[5]=10
Press any key to continue . . .
18. Computer Programming II
Inline Functions
• The use of macros in C allows short
“functions” to be called without the normal
overhead associated with function calls
• There are several characteristics of macros
that makes their use unsuitable for C++
• Thus, C++ introduced the notion of inline
functions to allow users to avoid the overhead
of function calls
• With inline functions, the compiler controls the
process (as opposed to the preprocessor, as
was the case in C)
19. Computer Programming II
Inline Functions
• How function calls work
– Recall that the result of compiling a computer
program is a set of machine instructions (an
executable program)
– When the program is run, the OS loads the
instructions into memory (associating each
instruction with a memory address) and then
executes the instructions in order
– When a function call is encountered, the program
“jumps” to the address of the function and then
“jumps” back when the function has completed
20. Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
inline int leap(int year);
int main()
{
int year;
cout << "Enter a year: ";
cin >> year;
if (leap(year))
cout << "The year " << year << " is a leap year" << endl;
else
cout << "The year " << year << " is not a leap year" << endl;
system("PAUSE");
return 0;
}
inline int leap(int year)
{
if (((year % 4) == 0) && (((year % 100) != 0) || ((year%400) == 0)))
return 1;
return 0;
}
Enter a year: 1999
The year 1999 is not a leap year
Press any key to continue . . .
Enter a year: 2000
The year 2000 is a leap year
Press any key to continue . . .
21. Computer Programming II
Inline Functions
• How functions work
– Each time the program “jumps” to execute a
function, there is associated overhead:
• “Loading” the function:
– The instruction immediately following the function call is
stored
– The function arguments are copied to a reserved region of
the stack
– Load the instruction referenced by the function call
• Terminating the function call:
– (Possibly) store a return value in a register
– Load the return instruction stored when the function was first
called
22. Computer Programming II
Inline Functions
• With inline functions, the compiler
replaces each instance of the function
call with the corresponding code
23. Computer Programming II
• The following example shows this insertion:
int main()
{
…
myFunction(2);
…
myFunction(5);
…
}
void myFunction(int n)
{
for (int i = 0; i < n; i++)
{
cout << i << “ “;
}
cout << “n”;
}
int main()
{
{ int n = 2;
for (int i = 0; i < n; i++)
{ cout << i << “ “; }
cout << “n”;
}
…..
{ int n = 5;
for (int i = 0; i < n; i++)
{ cout << i << “ “; }
cout << “n”;
}
}
24. Computer Programming II
Inline Functions
• The obvious overhead associated with
“jumping” to execute and return from a
function call is avoided
• However, there can be a significant memory
penalty for using inline functions
– Each time the compiler encounters an inline
function call, that call is replaced with the function
code
– Thus, if the inline function is called 20 times, 20
copies of it will be inserted into the program code
25. Computer Programming II
Inline Functions
• To define an inline function, insert the keyword inline
before the function definition
inline double square (double x) { return x * x; }
• Generally, inline function definitions should be placed
in a header file (for cleanliness and readability)
• When using inline functions, the function definition (or
the include statement if it’s in a header file) must be
placed before the first invocation of the function
26. Computer Programming II
Inline Functions
• Some notes on inline functions:
– You cannot inline recursive functions
– The keyword inline is only a suggestion to the
compiler, and may be ignore under certain
conditions, most notably if the function is
particularly large or complicated (such as functions
with frequent loops)
– Some functions that are not labeled with the inline
keyword may be inlined by the compiler
27. Computer Programming II
Inline Functions
• In general, using inline functions improves
program efficiency if:
– The function is small (so there is a measurable
savings realized by eliminating the function calling
overhead)
– The function is called often, but only occurs in a
small number of places in the program
• In other words, we want to realize these savings without
the memory cost associated with replicating the function
definition in many places
• An example would be a simple function that is called many
times in a loop
28. Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
void swap_int (int &a, int &b);
void swap_float (float &a, float &b);
void swap_char (char &a, char &b);
int main()
{
int i1 = 3, i2 = 5;
float f1 = 3.14159f, f2 = 1.23f;
char c1='A', c2='B';
cout << "Integers before swap:" << endl;
cout << i1 << ", " << i2 << endl;
swap_int(i1, i2);
cout << "Integers after swap:" << endl;
cout << i1 << ", " << i2 << endl;
cout << "Floating points before swap:" << endl;
cout << f1 << ", " << f2 << endl;
swap_float(f1, f2);
cout << "Floating points after swap:" << endl;
cout << f1 << ", " << f2 << endl;
cout << "Characters before swap:" << endl;
cout << c1 << ", " << c2 << endl;
swap_char(c1, c2);
cout << "characters after swap:" << endl;
cout << c1 << ", " << c2 << endl;
system("PAUSE");
return 0;
}
void swap_int(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void swap_float(float &a, float &b)
{
float temp = a;
a = b;
b = temp;
}
void swap_char(char &a, char &b)
{
char temp = a;
a = b;
b = temp;
}
Integers before swap:
3, 5
Integers after swap:
5, 3
Floating points before swap:
3.14159, 1.23
Floating points after swap:
1.23, 3.14159
Characters before swap:
A, B
characters after swap:
B, A
Press any key to continue . .
.
29. Computer Programming II
Function Overloading
• Function overloading (aka function polymorphism)
allows functions in C++ to share the same name
• For example, imagine that we have a sorting algorithm
that we wish to use to implement functions for several
types, such as int and char
• Traditionally, we would have to use different names for
these functions
void mySortInt(int array[ ]) {…}
void mySortChar(char array[ ]) {…}
30. Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
void swap (int &a, int &b);
void swap (float &a, float &b);
void swap (char &a, char &b);
int main()
{
int i1 = 3, i2 = 5;
float f1 = 3.14159f, f2 = 1.23f;
char c1='A', c2='B';
cout << "Integers before swap:" << endl;
cout << i1 << ", " << i2 << endl;
swap(i1, i2);
cout << "Integers after swap:" << endl;
cout << i1 << ", " << i2 << endl;
cout << "Floating points before swap:" << endl;
cout << f1 << ", " << f2 << endl;
swap(f1, f2);
cout << "Floating points after swap:" << endl;
cout << f1 << ", " << f2 << endl;
cout << "Characters before swap:" << endl;
cout << c1 << ", " << c2 << endl;
swap(c1, c2);
cout << "characters after swap:" << endl;
cout << c1 << ", " << c2 << endl;
system("PAUSE");
return 0;
}
void swap (int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void swap (float &a, float &b)
{
float temp = a;
a = b;
b = temp;
}
void swap (char &a, char &b)
{
char temp = a;
a = b;
b = temp;
}
Integers before swap:
3, 5
Integers after swap:
5, 3
Floating points before swap:
3.14159, 1.23
Floating points after swap:
1.23, 3.14159
Characters before swap:
A, B
characters after swap:
B, A
Press any key to continue . . .
31. Computer Programming II
Function Overloading
• C++ allows us to reuse function names,
provided that certain requirements are
met
void mySort(int array[]) {…}
void mySort(char array[]) {…}
• Overloaded functions are distinguished
by their argument list
void myFunction(int a) {…}
void myFunction(char a) {…}
void myFunction(int x) {…} // Not permitted
void myFunction(int x, int y) {…}
32. Computer Programming II
Function Overloading
• Note that the return type of a function is not taken into account
when determining valid function overloading
void myFunction(int a) {…}
int myFunction(int a) {…} // Not permitted
• There are several reasons for this, including:
• If return type is the only distinguishing aspect, how would
we determine which function to use when return type is
ignored?
myFunction(13); // Which one to use?
• If both return type and argument lists differ, determining
how to resolve overloaded functions is not straight-
forward
33. Computer Programming II
Operator Overloading
• Operators, such as +, -, && and ++, can be
thought of as
• another type of function in C++
– As such, they can also be overloaded (and, in fact,
already are in many cases)
• For example, there is no difference in the syntax when you
add two integers vs. when you add two floating point
numbers
– We will discuss operator overloading in more detail
after we have introduced classes
34. Computer Programming II
Default Arguments
• C++ allows you to define default arguments for
parameters in your function prototype
void myFunction(int x = 5); // Default value of 5 for x
• The default value is used if an actual argument
is not provided for a function call
myFunction(37); // Called with argument 37
myFunction(); // Called with default argument 5
35. Computer Programming II
Default Arguments
• Default arguments must be added from right to
left in a function prototype
– Examples of valid default arguments:
void myFunction(int x, int y = 5, int z = 10);
void myFunction(int x = 2, int y = 5, int z = 10);
• Examples of invalid default arguments:
void myFunction(int x, int y = 5, int z);
void myFunction(int x = 2, int y = 5, int z);
36. Computer Programming II
Default Arguments
• Similarly, default arguments must be used
from right to left when the function is called
void myFunction(int x = 2, int y = 5, int z = 10);
• Examples of valid calls:
myFunction(); // Uses all default arguments
myFunction(5); // Uses defaults for y(5) and z(10)
myFunction(5, 3); // Uses default for z(10)
myFunction(5, 3, 7); // Uses no default arguments
• You cannot “skip over” default arguments:
myFunction(5 , , 7); // Invalid – this will not use the
// default argument for y(5)
37. Computer Programming II
Default Arguments
• Using default values can reduce the number of
overloaded functions
– Consider a function which calculates your travel
time based on a distance and average speed,
which we want to default to 65 mph
float getTime(int distance); // Default speed of 65 mph
float getTime(int distance, int speed);
• Clearly, we can rewrite this using default
arguments
float getTime(int distance, int speed = 65);
38. Computer Programming II
Default Arguments
• Generally, default arguments should only be
used when there is an obvious (and frequently
used) default value
– Oftentimes, the use of a default value will not be
the only thing that differentiates the
implementations of overloaded functions
– Avoiding using a default argument as a “flag” to be
fed to conditional statements
39. Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
double test (double a, double b = 7)
{
return a - b;
}
int main ()
{
cout << test (14, 5) << endl;
cout << test (14) << endl;
system("PAUSE");
return 0;
}
9
7
Press any key to continue . . .