26334 total geeks with 3498 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: Jun 30
June Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
Hi? Vladimir? It"s
Obama. The hackers
ARE BACK. Hello?
Are you still
there?
Intel joins
Alliance for
Wireless Power
LinkedIn DNS
hijacked, site
offline
Embezzler stings
IBM, Microsoft in
Japan
Quantum boffins and
bread-heads form
new VC fund
NASA serves up
Curiosity"s
billion-pixel
panorama
That
Microsoft-Nokia
merger you"ve been
predicting? It"s no
go
Microsoft caves on
Xbox One DRM and
used-game controls
Kim Dotcom victim
of "largest data
MASSACRE in
history"
Google preps wave
of machine learning
apps
Slashdot
US and Russia Set
Up Cyber Cold War
Hotline
Amazon Vows To
Fight Government
Requests For Data
2 Men Accused of
Trying To Make
X-Ray Weapon
Monsanto Executive
Wins World Food
Prize
Microsoft Launches
$100k Bug Bounty
Program
The Plight of Star
Wars Droids
Java API and
Microsoft"s
.NET API: a
Comparison
MakerBot Merging
With Stratasys
Microsoft Kills
Xbox One Phone-Home
DRM
Billion-Pixel View
of Mars Snapped By
Curiosity
Article viewer

A closer look at functions



Written by:TroPe
Published by:NeorageX
Published on:2004-10-24 06:00:35
Topic:C++
Search OSI about C++.More articles by TroPe.
 viewed 8711 times send this article printer friendly

Digg this!
    Rate this article :
This time we are going to introduce the newbie to C++ functions, while teaching scope, return values, prototyping, overloading, and recursion.

-------------------------------------------
C++ Functions - In Depth
-------------------------------------------
Written by Giovanni Tropeano 11/2004
Prepared for OSIX


<<< Table of Contents >>>

  • ...What is a function?
  • ...The scope of a function
  • ...Getting a value in return
  • ...Recursion
  • ...Prototyping
  • ...Overloading
  • ...Trope, why are you writing so many articles lately?



::: What is a function :::
A complex program is divided into modules, each of which performs a specific task. In C++, modules are created as functions.

To define a function, use the syntax:

return-type name (parameter list)
{
   statements
}

In this example, the return-type specifies the data type that the function returns.

When specifying the parameter list or the arguments for a function, declare each parameter separately even if the parameters are of the same data type.

::: The scope of a function :::
Functions that can access variables defined within the code block are private to the function. Such variables are called local variables. Memory is assigned to local variables when the function is called and unassigned when the function exit.

The rule for local variables does not apply to static variables, which are allocated memory when the function is called the first time. Static variables retain their values when modified within the same function. These variables are not available to the code outside the function - there are other ways to that.

::: Getting a value in return :::
The return statement enables a function to return a value to its caller. For example, a function adds two numbers, as shown below:

int add (int octoberOsixMembers, int novemberOsixMembers)
{
   int sum;
   sum = octoberOsixMembers + novemberOsixMembers;
   return sum;
}


In this example, the return statement returns the value, sum, which holds the total value of octoberOsixMembers and novemberOsixMembers. Control is returned to the next line of code.

For example, a function has the data type set to void, as shown below:

void add (int octoberOsixMembers, int novemberOsixMembers)
{
   int sum;
   sum = octoberOsixMembers + novemberOsixMembers;
}

In this example, the function does not return a value. Control is automatically returned to the place where the function was called.

You can include a return statement in void functions. This is called forceful return of control to the calling code.

::: Recursion :::
Recursion is the circular definition of a function. It is the ability of a function or a code block to call itself. In C++, functions can be recursive, otherwise this paragraph probably would not be here. :p

Let's take a look at some code...

Calculate the factorial of a number
int factr(int i)
{
   int answer;
   if (i == 1)
      return 1;
   answer = factr(i -1)*i;
   return answer;
}


Clear as day, right? If not, read on!...

In the above code, if the value of i is one, the value one is returned. The function begins recursing when the value of i is more than one. The function calls itself with the value of factr(i -1). It also stores the value of fact(i -1)*i in the variable answer.

When i reaches the value 1, recursion stops and the values of all the recursive calls returns the answer variable.

Note Copies of the same variables are created by storing different values at every call because the function is called repeatedly inside its own code, thus recursion!

::: Prototyping :::
Prototyping a function refers to declaring a function with its parameter list and return type. You can first declare all the functions in the program. The syntax for a function prototype is:

Type name(parameter1, parameter2...
parameter n);


Type refers to the return type of the function. name refers to the function name. parameter1, parameter2, and parameter n are optional arguments.

For example, the prototype for the function shown above is:

int factr(int i);


::: Overloading :::
Overloading a function refers to declaring and defining two methods with the same name but different parameter lists. The overloaded function called depends upon the parameter list. This code shows how function overloading is performed:

int add ()
{
   int tropePoints = 10;
   int sajPoints = 20;
   int sum;
   sum = tropePoints + sajPoints;
   return sum;
}
int add(int member1Points, int member2Points)
{
   int sum;
   sum = member1Points + member2Points;
   return sum;
}


In the above code, the function, add(), is defined twice with different parameters. The function add() returns the sum of two members points defined in the variable, tropePoints and sajPoints. The function add(int member1Points, int member2Points) returns the sum of the members' points by passing the values to the variables, member1Points and member2Points.

::: Trope, why are you writing so many articles lately? :::
Been asked this quite a bit lately, so...if you must know, I was layed off, and want to continue what I love to do, and that is program, and help people. This web site was a terrific find for me, and I really enjoy writing when I know people appreciate the effort.

On that note...

Trope!

Did you like this article? There are hundreds more.

Comments:
sfabriz
2004-10-25 16:50:18
int factr(int i)
{
   return (i==1)?1:factr(i -1)*i;
}


this is quicker and uses less memory ;)
TroPe
2004-10-25 18:54:41
sure does...thanks!
gnoblins
2004-11-10 11:31:05
program will crash if factr(0) or factr(-1).
TroPe
2004-11-11 02:41:34
yeah, I could have put code in to catch that, but the article was more about the actual functions function. Nice catch though. Very thorough.
Macavity
2004-11-14 18:51:37
Arrrgh! You beat me to the punch, I was gonna write one. Nice tutorial anyway, easy approach to the subject at hand but thorough as well. I give you a big WOOT!!!
TroPe
2004-12-13 16:51:59
thanks Macavity! appreciate the kind words.
zethyr
2004-12-26 13:47:49
Good artivle TroPe :D I actually forgot why overloading would be useful, but now I remember.. ;)
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
harry
Blog entry for Thu 28th Sep 12pm on Thu 28th Sep 12pm
Hi In school i want to net send my mates but hide who its coming off any ideas. no programs though as the machine in school sets off an alarm if it detects any batch files etc... thanks Harry


     
Your Ad Here
 
Copyright Open Source Institute, 2006