Could someone please explain to me what the following text in the bold does:
e.g.
exampleFunction(int square, int circle)
Why wouldnt you just use this:
exampleFunction()
{
int square;
int circle;
}
Printable View
Could someone please explain to me what the following text in the bold does:
e.g.
exampleFunction(int square, int circle)
Why wouldnt you just use this:
exampleFunction()
{
int square;
int circle;
}
those are the parameters. they are used to pass values to the function
example:
now you can call it like:Code:int squared(int x)
{
return x*x;
}
squared(2)
and it will return 4.
if you could send it the value (2), it wouldn't be able to return the result (4) because it would have nothing to work with.
they're like local variables (local to the function), only when you call the function you can give them a value.
In addition to what MadHatter, have said:
Function's parameters is the functions way to access variables that are declared outside the function itself...
you can also use global variables, or data members if you are making a class or struct.
Thanks guys, that helped alot
EDIT: MadHatter: Does that mean x becomes 2?
So basically this is to mak the function more flexible? I get ya
yes, in this case x becomes 2. it's sort of like this...
so using parameters makes it so you can use any value.Code://function
int func(int x)
{
return x*x;
}
//function call
int someVar = func(7);
/*This would be the same as*/
//function
int func()
{
return 7*7;
}
//function call
int someVar = func();
hopefully that helped a little, rather than confusing you more... ;)
I can't believe you're telling a newbie that he can use global variables. Why don't you just tell him to use void main?Quote:
Originally posted by ammar
you can also use global variables
Eminence, don't use global variables. It's bad for a number of reasons.
This may be a simple example, but when you get to coding examples it will be very difficult to debug a program that uses global variables. The only global identifiers you should use are constants. Also, global variables are diametrically opposed to the concept of data encapsulation. In short, don't use global variables.Code:// Bad
int num;
int square(int x);
int main()
{
cout << num << " squared is " << square(num);
}
// Good
int square(int x);
int main()
{
int num; // notice that all of the variables are declared within functions, in this case main
cout << num << " squared is " << square(num);
}