I'm just starting to get the hang on functions exept I don't know what the arguments of a function are for and why and how returning is done. Can anyone help?
Thanks
-Chris
I'm just starting to get the hang on functions exept I don't know what the arguments of a function are for and why and how returning is done. Can anyone help?
Thanks
-Chris
hey a supernewbie (haha, jk i'll help you out)
so if you wanted a function to add two ints:
int add_ints(int a, int b)
{
return a + b;
}
here is the basic format:
[return-type] func_name([argtype] arg, [argtype] arg,...)
{
//other code
return [return-type];
}
and btw using add_ints is this easy:
int add_ints(int a, int b) //make sure this is declared or prototyped first
{
return a + b;
}
int main(void)
{
int p, q, r;
cout << "enter 2 numbers" << endl;
cin >> p;
cin >> q;
r = add_ints(p,q);
cout << "sum is " << r;
return 0;
}
a function can take in any number of args (well for your purposes, but there is a limit) but only return one item.
Functions don't have a clue about anything except for whats in the function... The arguments are in case the function needs something outside of the funcion. i.e.
if you have a function
void outputname()
that asks the user for their name, then outputs it, your function would look like...
void outputname()
{
apstring name;
cout<<"Enter your name : ";
cin>>name;
cout<<name<<endl;
}
if you wanted the function to output a name that is given to it from outside the function, it would look like...
void outputname(apstring name) // to make a copy of name
or
void outputname(apstring &name) // to make a reference to name
{
cout<<name<<endl;
}
<^>( * ; * )<^>
Well, I'm not that much of a super newbie, its just functions and classes which I can't seem to get the hang of
Anywayz, i've written programs that use and call functions without the use of arguments or returning. What is the purpose of arguments and returning?
Arguments allow you to pass information to a function.
For ex.
int mult(int x, int y)
{
return x*y;
}
Now when I want to multiply two numbers i can just say this:
mult(5, 6);
What this will do is set x to equal 5 and y to equal 6 then it'll run the function.
Returning allows you to get a value from a function.
For ex.
int a = mult(5, 6);
What this will do is create an integer called "a" then run the function mult and set a to equal whatever mult returned which in this case would be 5*6.
Hope this helps.
Oops! Forgot to log in when I posted that.
Arguments can also be passed by value or by reference.
Default is by value. This makes a copy of the argument, passes it to the called function, does whatever, and ends. The original value is not modified, and the passed value is typically destroyed after the called function is done.
By reference passes a reference to the original value, which then can be modified. This can be good, or bad, depending on what you're doing.