Hey everybody,it's the c++ creator.I am a beginner at C++,and am getting confused at functions.I am learning from a site called cprogramming.com and this is what they say-

Lesson 4: Functions
(Printable Version)

Now that you should have learned about variables, loops, and conditional statements it is time to learn about functions. You should have an idea of their uses as we have already used them and defined one in the guise of main. cin.get() is an example of a function. In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive.

Functions that a programmer writes will generally require a prototype. Just like a blueprint, the prototype tells the compiler what the function will return, what the function will be called, as well as what arguments the function can be passed. When I say that the function returns a value, I mean that the function can be used in the same manner as a variable would be. For example, a variable can be set equal to a function that returns a value between zero and four.

For example:


#include <cstdlib> // Include rand()

using namespace std; // Make rand() visible

int a = rand(); // rand is a standard function that all compilers have

Do not think that 'a' will change at random, it will be set to the value returned when the function is called, but it will not change again.

The general format for a prototype is simple:


return-type function_name ( arg_type arg1, ..., arg_type argN );

arg_type just means the type for each argument -- for instance, an int, a float, or a char. It's exactly the same thing as what you would put if you were declaring a variable.

There can be more than one argument passed to a function or none at all (where the parentheses are empty), and it does not have to return a value. Functions that do not return values have a return type of void. Let's look at a function prototype:


int mult ( int x, int y );

This prototype specifies that the function mult will accept two arguments, both integers, and that it will return an integer. Do not forget the trailing semi-colon. Without it, the compiler will probably think that you are trying to write the actual definition of the function.

When the programmer actually defines the function, it will begin with the prototype, minus the semi-colon. Then there should always be a block with the code that the function is to execute, just as you would write it for the main function. Any of the arguments passed to the function can be used as if they were declared in the block. Finally, end it all with a cherry and a closing brace. Okay, maybe not a cherry.

Let's look at an example program:


#include <iostream>

using namespace std;

int mult ( int x, int y );

int main()
{
int x;
int y;

cout<<"Please input two numbers to be multiplied: ";
cin>> x >> y;
cin.ignore();
cout<<"The product of your two numbers is "<< mult ( x, y ) <<"\n";
cin.get();
}

int mult ( int x, int y )
{
return x * y;
}

This program begins with the only necessary include file and a directive to make the std namespace visible. Everything in the standard headers is inside of the std namespace and not visible to our programs unless we make them so. Next is the prototype of the function. Notice that it has the final semi-colon! The main function returns an integer, which you should always have to conform to the standard. You should not have trouble understanding the input and output functions. It is fine to use cin to input to variables as the program does. But when typing in the numbers, be sure to separate them by a space so that cin can tell them apart and put them in the right variables.

Notice how cout actually outputs what appears to be the mult function. What is really happening is cout is printing the value returned by mult, not mult itself. The result would be the same as if we had use this print instead


cout<<"The product of your two numbers is "<< x * y <<"\n";

The mult function is actually defined below main. Due to its prototype being above main, the compiler still recognizes it as being defined, and so the compiler will not give an error about mult being undefined. As long as the prototype is present, a function can be used even if there is no definition. However, the code cannot be run without a definition even though it will compile. The prototype and definition can be combined into one also. If mult were defined before it is used, we could do away with the prototype because the definition can act as a prototype as well.

Return is the keyword used to force the function to return a value. Note that it is possible to have a function that returns no value. If a function returns void, the return statement is valid, but only if it does not have an expression. In other words, for a function that returns void, the statement "return;" is legal, but redundant.

The most important functional (Pun semi-intended) question is why do we need a function? Functions have many uses. For example, a programmer may have a block of code that he has repeated forty times throughout the program. A function to execute that code would save a great deal of space, and it would also make the program more readable. Also, having only one copy of the code makes it easier to make changes. Would you rather make forty little changes scattered all throughout a potentially large program, or one change to the function body? So would I.

Another reason for functions is to break down a complex program into logical parts. For example, take a menu program that runs complex code when a menu choice is selected. The program would probably best be served by making functions for each of the actual menu choices, and then breaking down the complex tasks into smaller, more manageable tasks, which could be in their own functions. In this way, a program can be designed that makes sense when read. And has a structure that is easier to understand quickly. The worst programs usually only have the required function, main, and fill it with pages of jumbled code.

Could anybody explain this?

Thanks in advance,
c++ creator

Is there anything specific you do not understand as there is a lot of information from

the beginning

to

the end.

Possibly explain what you do understand and then we can help with the rest. Otherwise what we would need to do is create a response that is nothing but a complete tutorial of what a function is.

No,like what is a prototype?You would not believe this,but I am just 10 years old and I am trying to program.It's true.Just because I like to code,I know a quite a lot of HTML too.Reply.

c++ creator

Hey, that's cool. Doesn't matter if your 10 or 50, we all have the same goal here. We are here to learn, so kudos to you.


A prototype that they are discussing above is the data type or void that is prior to the function name.

void test();

void is the prototype and test is the function name. This is the only function that does not require a -return- in the function definition.

int time();

int is the prototype (data type) and time is the function name. This, like all other data types, requires a return statement in the function definition. Such as this next example.

int time(){     // function definition, { is the start of the block of code

int minutes = 60;
int seconds = 60;

int hours = minutes * seconds;
return hours;
} // end of block of code, end of function definition
// hours is of type int. The function, int time(), requires the return to be of int value. If hours was a type double, float, or any non integer then the compiler would likely give an error.

Functions are made for code that is anticipated to be frequently used. Later on you will learn about classes and functions. That's where the fun begins.

Are you a Youtube user?If then could you create a tutorial on functions?

Correction: The function prototype is that which is declared above before you even start the actual coding, before the main function even. It's used as a reference to the actual function later to kind of double check if everything is in order.

Thanks Saith and Cross213,though what does Cross213 mean by

It's used as a reference to the actual function later to kind of double check if everything is in order.

?

Thanks Saith and Cross213,though what does Cross213 mean by?

He means (I hope) that the prototype introduces enough information about a function to safely call it without requiring the function's definition to be visible.

Sorry, sorry. Cross213 is right. I misread it. I usually use the word "declaration" instead of "prototype".


int time(); // is the declaration or prototype of the function. This needs to be stated prior to the definition of the function. Functions need to be declared prior to the main() function.

.. example ..

int time();           // prototype, or declaration of a function. Basically declaring the use of this function -prior- to it being -called- in the main() function. 

int main(){

//block of code
return 0;
}

int time(){     // function definition, { is the start of the block of code

int minutes = 60;
int seconds = 60;

int hours = minutes * seconds;
return hours;
} // end of block of code, end of function definition. This function is still has the data type of int, so an int is still required as the return type.

As Narue was stating, 'He means (I hope) that the prototype introduces enough information about a function to safely call it without requiring the function's definition to be visible. "

Later on, you are allowed to have the -function definition- in another file, but the declaration (prototype) needs to be in the current file if you plan on using that function.

Functions need to be declared prior to the main() function.

To be precise, functions need to be declared before they can be called.

You're so helpful, Narue :D

c++ creator is now cadence441.See my status,it shows I am banned!What wrong did I do?I wasn't even able to send a message to somebody.

You're banned because you're underage. Please do not post again or I'll ban cadence441 as well.

I didn't realise there was an age limit. Could you let me know what it is. I'm 3 years old by the way.

I didn't realise there was an age limit. Could you let me know what it is. I'm 3 years old by the way.

While I'll admit that I'd overlooked this myself, the age limit is spelled out in the Acceptable Use Policy:

Minimum Age Requirement
In compliance with the U.S. Coppa Act, no one under the age of thirteen (13) is permitted to register on these forums. If someone under the age of 13 does register, it is understood that they are doing so against DaniWeb's policies and without DaniWeb's knowledge.

Looking up the Children Online Privacy Protection Act (COPPA), it would be a violation to collect details such as names and locations for individuals under the age of 13 without written parental permission, or at least that's what I understand it to say - I don't have my Legalese to English dictionary on hand right now. It seems to me that, while there would be ways to accommodate underage members, the trouble needed to allow for it would be far too much to deal with feasibly.

I'll be back in a decade.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.