Understanding Functions

Hey there fellow coders, I'm having a little bit of a hard time understanding functions. What is a function prototype? What is an example? Hell I just need some guidance to some information that makes is easy to understand.

I need to make a program that uses a few functions and I'm not sure if I get the whole concept. An example would be

Define a make_sterling function that takes thee integers representing pounds,
shillings, and pence (in that order) and returns a sterling structure.

would this be done in my header file or just the .cpp file? help? thanks
Let's say you want to go and buy some bread. You go into the bread store and ask for some bread at a price. You give the cashier some money and the cashier in turn gives you bread. Functions are kinda the same idea:

1
2
3
4
5
6
7
8
9
10
11

Bread BuyBread(float Price)
{
    if(BreadPrice == Price)
      {
         cout<<"Here is some Bread"<<endl;
         return Bread;
       }
   
      return 0;
}


The above function called BuyBread returns a bread when you send it a price.

So now anytime any part of your program wants to buy bread, you just call buy bread.

There's more to this, but that's kinda the idea.
That makes it a little easier; given the example, would it look like this?:

1
2
3
4
5
6
7
8
9
10
11
	struct sterling
{
  int pounds;
  int shillings;
  int pence;
};

sterling make_sterling (int p, int s, int pe);
sterling make_sterling (int s);
void print (Time a_Time);
sterling add (Time t1, Time t2);



//mind you this is kinda hacked together from some older code and various stuff so i apologize
Functions can be declared and defined in either the header file of the cpp file, but not both.

You can have a function declaration in the header file:
//.h file
Bread BuyBread(float);

//.cpp file
Bread BuyBread(float Price)
{};

But you cannot declare and define a function or class in both header and source file.
That makes a little more sense. so what would be the advantage of a header file?
A function is basically like a program inside of a program.. you take a block of code and name it whatever you want your function name to be. If you need it in the future you would call on it from wherever you want it to work from.. lol sorry i dont think I explained it very well but hopfully you get it :). Happy coding!!
Topic archived. No new replies allowed.