Originally Posted by
BIGBOPPER
I am getting stuck on functions, and loops.
I remeber the days of basic, especially "TI basic".
Loops
If you mean the "BASIC" language in Texas Instruments calculators, that's more of a subset of BASIC. It's BASIC-ish. Are you conditioned to loop by using GOTOs back to a label or line number ahead of the statements to be repeated? If so... stop it. :)
GOTOs make code hard to maintain. Most C/C++ loops consist of a block of code with a condition that is tested either at the beginning of the block or at the end of the block that determines whether to repeat the block.
There is...
Code:
do {
/* ... bunch of stuff ... */
} While ( ThisExpressionIsTrue );
or
Code:
While ( ThisExpressionIsTrue ) {
/* ... do bunch of stuff ... */
};
See the
Control Structures section of the tutorial I linked in my prior post. There is also a
for loop typically used for looping a set number of times while a counter is incremented.
Functions
Are nothing more than a group of statements that are given a name and then referenced elsewhere in the program by the name:
Code:
void MyLongInvolvedFunction(void);
int main(void) {
/* ... do some stuff ...*/
// Call my long involved function...
MyLongInvolvedFunction();
/* ... do some more stuff ... */
// Call my long involved function, again...
MyLongInvolvedFunction();
/* ... do yet more stuff ... */
// Call my long involved function, yet again...
MyLongInvolvedFunction();
};
void MyLongInvolvedFunction(void){
/*
My long involved function is 500 lines of code.
I'm too lazy to type 500 lines of code in my
main routine every time I need it, so I stick
it in this function that I can call by a short name.
*/
/* ... do some seriously complicated stuff ... */
};
Info (parameters) can also be given (passed) to the function to play with when it is called.
Code:
/*
Following function declaration gives the function
an int value and a long value to play with,
function then returns an int when done.
*/
int MyFunction(int MyInt, long MyLong);
The concept of scope comes into play here. In BASIC it is typical for all variables to be global in scope, meaning they can be referenced anywhere in the program regardless of the code module (file) they are declared in, or subroutine they are used in. In C/C++, the variables MyInt and MyLong in the example above exist only within the function. When the function is called with a another variable such as:
Code:
MyFunction(Count, BigNumber);
any changes MyFunction makes to the value of MyInt (which begins life with the value of Count) will not be reflected in the value of Count. The variable Count and MyInt have separate memory locations when the program executes. For MyFunction to directly change Count, the memory address of Count would be passed as a pointer reference like:
Code:
int MyFunction(int *MyInt, long MyLong);
but that's another discussion.