Advertisement

function parameters and arguments

Started by July 26, 2002 12:01 AM
4 comments, last by Mikey21 22 years, 3 months ago
I''ve been reading a book on C++, and there''s this section on parameters and passing arguments. I sort of understand how this works, but could someone please tell me what they are used for?
This really belongs in the beginners forum.

Long story short, though, function arguments are the same in programming as they are in math. Remember seeing stuff like this?

x = cos(t)

t is an argument to the function "cos".


Don''t listen to me. I''ve had too much coffee.
Advertisement
Sorry, this should have gone in the beginner''s forum; my bad. Hopefully a mod will move it. Anyway, could you please elaborate on that a bit? In x=cos(t) how does t affect the rest of the function? I didn''t take calculus and didn''t do that well in algebra 2/ trig either.
What he meant by x = cos(t) is that you are passing the variable t to the function cos(), and this function takes that variable and does stuff with it, and then returns a value and x becomes this value.

for example:

float cos(int someVar)
{
//does stuff with the someVar variable
return value;
}

and you call this:

x = cos(t);

Did that help?
without parameter passing, functions would be a lot less useful that they are. the point of having them is to allow us to break our code up into named segments and black boxes. they allow us to create more managable, readible code. normally, without functions, you might have a lot of global, or public variables, exposed at filescope. when you write functions, variables are declared as automatic , meaning they only exist within the scope of the function -in this case, you must pass variables to a function for it to have access to them.



      //a global variable, exposed to all functions in this file (not necessarily a bad thing, but probably not good)int t = 10;int add(int x, int y){ int z = 5; // a local declaration return x + y + z; //use various args to do work, and return results to caller}main(){ int x = add( 5, 6) + t; //x = 26}      


technically, you could get away with declaring all variables globaly -however, youwouldnt be programming in a very modern or effecient fashion, and would probably be called a poor programmer.


[edited by - evilcrap on July 27, 2002 6:22:51 AM]
Thanks a lot!!! I''ve read that section over and over and never got much of it until now, thanks guys.

This topic is closed to new replies.

Advertisement