Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
4 views
COSC - 301 - Lecture - Notes Function
Function in OOAD
Uploaded by
abubakarumarfarouq667
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save COSC_301_lecture_notes Function For Later
Download
Save
Save COSC_301_lecture_notes Function For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
4 views
COSC - 301 - Lecture - Notes Function
Function in OOAD
Uploaded by
abubakarumarfarouq667
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save COSC_301_lecture_notes Function For Later
Carousel Previous
Carousel Next
Save
Save COSC_301_lecture_notes Function For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 13
Search
Fullscreen
The C++ Lagguage Tutorial Functions (1) Using functions we can structure our programs in a more modular way, accessing all the potential that programming can offer to us in C++. Structured ‘Atunetion is a group of statements that is executed when itis called from some point of the program, The following is its format type ane ( paraneteri, paraneter2, ...) where: = type is the data type specifier of the data retumed by the function. ‘* none is the identifier by which it will be possible to call the function. © paraneters (as many as needed): Each parameter consists of 2 data type specifier followed by an Identifier, ike any regular variable declaration (for example: ‘at. x) and which acts within the function as 2 regular local variable. They allow to pass arguments to the function when itis called. The different parameters are separated by commas. ‘¢statenents is the function's body. It isa block of statements surrounded by braces { Here you have the first function example: 77 function example (The result i# 8 Sincluce
Using nanespace star lint addition (int a, int b) “ return (217 » 2 = addition (5,3) return 0) In order to examine this code, first of al rememiaer something said at the beginning of this tutorial: a C++ program always begins its execution by the na-a function. So we will begin there. We can see how the sain function begins by declaring the variable = of type in. Right after that, we see a call to fa function called aston. Paying attention we will be able to see the similanty between the structure of the call to the function and the declaration of the function Itself some code lines above: int addition (int 2, int h) 1 Tt zmaddition, 5, 3 ); ‘The paremeters and arguments have a clear correspondence. Within the ma: function we called to aéei tion passing two values: 5 and 3, that correspond to the int a and int b paremeters declared for function addition, 41 © gia Uh oe[At the point at which the function is called from within za:n, the control Is lost by main and passed to function adds tion, The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and nt bp within the function. Function acai tion declares another local variable (int =), and by means af the expression r=a+b, It assigns to = the result of « plus 5. Because the actual parameters passed for » and » are 5 and 3 respectively, the result is 8 ‘The following line of code: return (ely finalizes function addsson, and returns the contral back to the function that called it in the first place (in this case, sain). At this moment the program follows it regular course from the same point at which it was interrupted by the call to ada: cion. But additionally, because the return statement in function acdition specified a value: the content of variable x (cetixn {r)7), which at that moment had a value of 8, This value becomes the value of ‘evaluating the function call int addition (int a, int h) # =z addition (¢ 7, 2); So being the value returned by a function the value given to the function cal itself when itis evaluated, the variable = will be set to the value returned by aceiition (5, 2), that is 8, To explain it another way, you can imagine that the call to a function (acidition (5,3)) is literally replaced by the value it returns (8). ‘The following line of code in main is: cout << "The result is" << 27 ‘That, as you may already expect, produces the printing of the result on the screen. 42 lap ae4 The C++ Lagguage Tutorial [Scope of variables [The scope of variables declared within a function or any other inner block is only thelr own function or their own block and cannot be used outside of them. For example, in the previous example it would have been impossible to lise the variables 2, » or r directly in function main since they were variables local to function nas: ton. Also, it ‘ould have been Impossible to use the variable = directly within function acition, since this was a variable local to the function mai Winclude
int Integer; char achavanter char string (201; (Global variables unsigned int Numbexofsons main 0) t unsigned short Age; flual atiunber, Auvller0ne; Local variables cout << "Entex your age:" aon mn astructioms ee [Therefore, the scope of lacal variables is limited to the same block level in which they are declared. Nevertheless, |we also have the possibilty to declare global variables; These are visible from any point of the code, inside and utside all functions, In order to declare global variables you simply have to declare the variable outside any junction or block; that means, directly in the body of the program. ‘And here is another example about functions: 43 © gia Uh oewet The C+ ee Tutorial 77 function example fhe first resuit is 5 Sincluce
The second result 9 5 Using nanespace star The thira resuit is 2 The fourth reqult 19 6 int subtraction (int a, int b) a return (2) » int 25, 23, 2 2'= subtraction (7,2) Fout << "rhe first result ss" ¢< 2 << ‘\ntz cout << “the second result is "<< subtraction (7,2) << ‘\nt cout << "the third result de" << subtraction (x,J) << "\a"z cout << "the fourth result is" <¢ << ‘\n return 07 In this case we have created a function called subtraction. The only thing that this function does is to subtract both passed parameters and to return the result. Nevertheless, if we examine function sain we will see that we have made several calls to function subeeaction ‘We have used some different calling methods so thet you see other ways or moments when a function can be calle. In order to fuly understand these examples you rust consider once again that a call to function could be repleced by the value that the function call itself is going to return, For exemple, the first case (that you should already know because Its the same pattern that we have used in previous exemples): fe = subtraction (7,277 Gout
using nanespace star void printaessage 0 ‘ cout << "r'm a function!" » recur 07 n woud can also be used in the function's parameter list to explictly specify that we want the function to take no actual parameters when It is called. For example, function printessage could have been declared as: woid printmessage (void) c Although itis optional to spectty void in the parameter list. In C+, a parameter list can simply be left blank if we want a function with no parameters. 45 © gia Uh oe‘What you must always remember is that the format for calling @ function includes specifying its name anc ‘enclosing its parameters between parentheses, The non-existence of parameters does not exempt Us fram the ‘obligation to write the parentheses. For that reason the call to printmessaze Is: printnessage 07 ‘The parentheses clearly indicate that tis is a cal to a function and not the name of a variable or some other C++ statement. The following call would have been incorrect: printmessage: 46 lap aeThe C++ Lagguage Tutorial Functions (II) Arguments passed by value and by reference. Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. ‘This means that when calling 2 function with parameters, what we have passed to the function Ware copies of their values but never the variables themselves. For example, suppose that we called our first function addition using the following code: g's addition (x.y 17 What we did in this case was to call to function addition passing the values of x and y, he. § and 3 respectively, but not the variables x and y themselves. int addition (int a, int b) tT Tf zm addition ( 5, 2 ); This way, when the function addition Is called, the value of its local variables « and » become s and 2 respectively, but any modification to elther » oF » within the function addition will not have any effect in the values of » and y ‘outside It, because variables » and y were not themselves passed to the function, but only copies of thelr values ‘the moment the function was called But there might be some cases where you need to manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference, as in the function duplicate of the following example: 77 passing parameters by reference ae aA ‘include ctostream> using nanespace star roid duplicate (inte a, inte by inte c} » ant main 0 ‘ int xe, 3, 2 dupticate (x;y 21 return 0 nec y cet) tc ‘The fist thing that should call your attention Is that in the declaration of dup2scate the type of each parameter was followed by an ampersand sign («). This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value. When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local varlables will have an effect in thelr ‘counterpart variables passed as arguments in the call to the function. 47 © gia Uh oeThe C++ Lagguage Tutorial void duplicate (inte a,inte b,inte c} bob oF duplicate ( x , Yo, Ei) ‘To explain it in another way, we associate a, is and c with the arguments passed on the function call (x, y and =) land any change that we do on a within the function wil affect the value of x: outside It. Any change that we do on » will affect y, and the same with < and 2. ‘That is why our program's output, that shows the values stored in x, y and « after the call to duplicate, shows the ‘values of all the three variables of main doubled, If when deciaring the following function Wwoid duplicate (nts a, inte b, inte el we had declared It this way: Wold duplicate (int a, int by int el |e, without the ampersand signs («), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and = without having been modified. Passing by reference is also an effective way to allow a function to return more than ane value. For example, here is a function that returns the previous and next numbers of the fist parameter passed, [7 more than one returning value Previous-99, Wext=i02 include
using nasespace sta void provnext (int x, inte prev, inte next) prev = xi: » « Ant 2-200, y, 21 provnext, (x) yr 2) cout ce "Previous-"
Using nanespace star int divide (int a, int b=2) return (2) » int sain 0 i cout << divide (22); cout << endl Fout << divide (20,4)7 return 07 [As we can see in the body of the program there are two calls to function divide. In the frst one: divide (2) ‘we have only specified one argument, but the function aivide allows up to two. So the function divide has assumed that the second parameter is 2 since that is what we have specified to happen If this parameter was not passed (notice the function declaration, which finishes with int b=2, not just snt ). Therefore the result of this function calli 6 (22/2). In the second cal aivide (@o,47 there are two parameters, so the default value for » (int b=) Is ignored and » takes the value passed as argument, that is 4, making the result returned equal to 5 (20/3). “9 SeeThe C++ Lagguage Tutorial Overloaded functions. In C++ two different functions can have the same name if their paremeter types or number are diferent. That means that you can give the same name to more than one function if they have either @ ciferent number of parameters or cifferent types in their parameters, For example: (77 overloaded function 0 Hinclude
2s using namespace stdz lint operate (int a, int b) ‘ return (a*b); 0 ‘float operate (float a, float b) return (a/b) » ant main 0) « float me3.0,n=2.07 cout <2 operate iey)s cout
r= 362880 ong factorial (long a) sf a> return (a ¢ factorial (a-i)}: return (2)7 » cout ce "Pleas return 0 type a nunber: * Notice how in function raccorial we included 2 call to itself, but only if the argument passed was greater than 1, since otherwise the function would perform an infinite recursive loop In which ence It arrived to 0 it would continue multiplying by all the negative numbers (probably provoking a stack overflow error on runtime. ‘This function has a limitation because of the data type we used in its design (ons) for more simplicity. The results sven will not be valid for values much greater tian 101 or 151, depending on the system you compile it, Declaring functions. Until now, we have defined all ofthe functions before the first appearance of calls to them in the source code. ‘These calls were generally In function main waich we have always left at the end of the source code. If you try to repeat some of the exemples of functions described so far, but placing the function main before any of the other functions that were called from within it, you will most likely obtain compiling errors. The reason is that to be able to calla function it must have been declared in some earlier point of the code, lke wie have cone in all our examples. But there is an alternative way to avoid writing the whole code of a function before it can be used in main or in some other function. This can be achieves by declaring just a prototype of the function before itis used, instead of the entire definition. This declaration is shorter than the entire defin‘tion, but significant enough for the compiler to ‘cetermine its return type and the types ofits perameters. Its form is: st © gia Uh oeTutorial The cote type mane ( arguxent_typel, argument type2, .-.14 Its identical to a function definition, except that it does not include the body of the function itself (Le., the function statements that in normal definitions are enclosed in braces { }) and instead of that we end the prototype edlaration with a mandatory semicolon (;) ‘The parameter enumeration does not need to Include the identifiers, but only the type specifiers. The inclusion of @ ame for each parameter as in the function definition is optional in the prototype declaration. For example, we can eclare a function called protofunction with two sn parameters with any of the following declarations: gt peotofunction (int Hirst, int secondly list protofunction (lat, iat)? Anyway, including a name for each variable makes the prototype more legible. 7 deciaring functions prototypes ffype a number (0 te exit: 9 ‘include
umber 13 oad. using nanespace star ‘Type @ nunber (0 to exit): 6 Nober is oven oid odd tint aly ‘Type a number (0 to exit): 1030 oid even (ine als Nunber 1s even ‘Type a number (0 to exit): 0 int main 0 Number is even. i at cout << "Type a nunber (0 te exit): “7 edd i Pwnite ino) return 07 » void edd (int a) Qi Sf ((at2) !~0) cout << "Nunber Se odd.\n"7 else even (a7 » void even (int a} « Af ((a82)—-0) cout << "Munber is even.\n"s else odd (a) » ‘This example is indeed not an example of efficiency. I am sure that at this point you can already make 2 program with the same result, but using only half of the cade lines that have been used in this example. Anyway this ‘example illustrates How prototyping works. Moreover, in this concrete example the prototyping of at least one of the two functions is necessary in order to compile the code without errors, ‘The first things that we see are the decleration of functions ox and even’ wold odd (iat aby woid even (int als This allows these functions to be used before they are defined, for example, in main, which now is located where ‘some people find it to be a more logical place for the start of & program: the beginning of the source code. ‘Anyway, the reason why this program needs at least one of the functions to be declared before itis defined Is. because in ods there is a callto even and in even there isa call to add. If none of the two functions had been 82 lap aepreviously declared, a compilation error would happen, since either od would not not be visible from even, (because it has still not been declared), or even would not be visible from ox (for the same reason). Having the prototype of all functions together in the same place within the source code is found practical by some programmers, end this can be easily achieved by declaring al functions prototypes at the beginning of a program. 53 lap ae
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6125)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brene Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (932)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8214)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Tóibín
3.5/5 (2061)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2641)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Victoria Walters
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Yes Please
From Everand
Yes Please
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel