Page 1 of 1
using functions
Posted: Mon May 10, 2010 10:55 pm
by Randi
lets say I code like the following, am I able to pass the integer flame through both functions? or would I have to do something like the second code?
Code: Select all
int flame;
void candlestick();
void setflame();
candlestick()
{
flame = 2;
setflame();
}
setflame()
{
if (flame == 2)
cout << "flame is at 2";
}
Code: Select all
int flame;
void candlestick(int);
void setflame(int);
candlestick(int flame)
{
flame = 2;
setflame(flame);
}
setflame(int flame)
{
if (flame == 2)
cout << "flame is at 2";
}
Re: using functions
Posted: Mon May 10, 2010 11:21 pm
by Live-Dimension
If I remember how globals work in c++ (the closest I use is namespace variables, globals should never need to be used), the first one should work fine once you fixed the compile errors. Why didn't you simply test it? Also, each function definition needs the return type, in this case, void before the function name. The second one works, but only by sheer chance of the way you did it. It would never work any other way.
This is the most basic of c++. Buy a book, or at least go through some tutorial sites. There are plenty of references to decent c++ resources around
here and
here.
Re: using functions
Posted: Tue May 11, 2010 12:35 am
by Bakkon
Your functions in the second example need to be pass by reference.
Code: Select all
void candlestick(int&);
void setflame(int&);
edit: Wait, hold on, I'm drunk. You're doing something different, I think.
Re: using functions
Posted: Tue May 11, 2010 1:33 am
by Live-Dimension
Bakkon wrote:Your functions in the second example need to be pass by reference.
Code: Select all
void candlestick(int&);
void setflame(int&);
edit: Wait, hold on, I'm drunk. You're doing something different, I think.
That's true, however References are far beyond Randi's skill currently, hence why I didn't mention it. Really Randi, find a tutorial site or book or something and learn c++ that way.
Re: using functions
Posted: Tue May 11, 2010 8:48 am
by Falco Girgis
The first method would work, because the variables are declared globally. The second method will not work, because each time you pass the integer to a function, it's making a duplicate integer (since you aren't using pass-by-value).
Both examples are considered "shitty design." There is never a good reason (in C++) to have free-floating global-variables like the first example.