Functions

Started by
29 comments, last by Xai 17 years, 7 months ago
Quote:Original post by bam104
See this is where i get confused between functions and classes...

When programming the recipie NotAYakk posted above, wouldnt this be done with some kind of "medium boiled egg class" that is called by the "fancy egg class" which is initiated by main or recipie loop?

Apologies if im crazy here.


probably not. There are many ways to break an egg, and in object oriented programs, even more ways to arange your code and classes. But here's a few likely ideas.

Idea 1 - the cook.

You would have a Chef class which had functions for each of the recipes he knows how to make. Things like BoilEggsMedium and MakeFancyEggs.

Idea 2 - the kitchen model.

You would have a Utilsil and Appliance classes like Oven, Microwave, Spatula, etc (like audio, graphics and interface devices in games). These would be instantiate at program start as contained members of a Kitchen class. You would have a Recipe class or interface, and dozens of Recipe instances such as "Fancy Eggs" (these are kind of like AI scripts). You would have a Chef class, which nows how to "read" recipes and "use" kitchen equipment (this is kind of like the master controller / main opponent AI).
Advertisement
For those confused about classes... Do you know what a struct is?

A struct and a class are the same thing. :)

Classes or Structs hold information.
Functions manipulate information.

...

Now, things do get blurry and confusing when you try more advanced things. Your Classes can have Functions attached to them (called Methods), and you can write Functors which are Classes that act as Functions.

But at the core -- Classes hold and define data. Functions manipulate and change data.
Now I need help with global and local variables. I know that local variables are used in the function itself, and global variables can be used by all functions, but in this code, how does addNums get num1 and num2.
#include <iostream>#include <conio.h>using namespace std;int addNums( int num1, int num2 );int main(){    int num1, num2;        cout << "Enter the first number: ";    cin >> num1;    cout << "Enter the second number: ";    cin >> num2;    cout << "The numbers added equal: " << addNums ( num1, num2 ) << endl;        getch();    return 0;}int addNums( int num1, int num2 ){    return num1 + num2;}
Quote:Original post by Kenny77
Now I need help with global and local variables. I know that local variables are used in the function itself, and global variables can be used by all functions, but in this code, how does addNums get num1 and num2.


They are passed in via the main() function. The line:
cout << "The numbers added equal: " << addNums ( num1, num2 ) << endl;
passes whatever is set into num1 and num2 into the function addNums. In both the main function and the addNums function you are working with local variables.
[source lang='cpp']#include <iostream>#include <conio.h>using namespace std;// our global variabelesint num1 = 10int num2 = 23;int addNums(int num1, int num2);int main(){   cout << "3 + 4 = " << addNums(3, 4) << endl;   cout << "Global values: num1 = " << num1 << " and num2 = " << num2 << endl;   getch();   return 0;}int addNums(int num1, int num2){   // be aware! although num1 and num2 are global variabeles,   // this function has local variabeles with the same name.   // What happens is that the local variabeles are used, which are   // set to 3 and 4 respectively when the function gets called.   // If the global vars had been used, the result would've been 33.   return num1 + num2;}


There's an example with global variabeles. Notice that local variabeles override global ones, e.g. when a function or scope has variabeles with the same name, the local ones are used. The global ones don't get overwritten, they're just not accessible at that moment. That's something to be aware of. Usually it's best to keep as little global stuff as possible, as dividing makes it easier to conquer, or so they say. :)

Go ahead and experiment, writing those values to the console from within main() and within addNums(). I'm sure you'll find out what's going on exactly.
Create-ivity - a game development blog Mouseover for more information.
stop using the same names for your function parameters and your variables and it will make your learning easier.

for instance don't do this:

int square(int x)
{
return x * x;
}

int main()
{
int x = 5;
int square = square(x);
}

instead do this:

int square(int number) // or value, arg, param, i or whatever
{
return number * number;
}

int main()
{
int value1 = 5;
int value2 = square(value1);
}

see in this version, the same word is never used for 2 different things, so you can read it and not get as confused.

In the real world, it is common for the variable and parameter names in your program to be the same many times, but once you learn more you won't be confused by it (you will be able to see which "thing" each word is refering to. Right now, avoid it ... I recommend avoiding it for 2-3 months.

But anyway, that said, here's some more info about it.

In C and C++ a variable name is looked up following a sequence of rules that normally follow some semblance of nesting.

here's a silly example to illustrate:

int x = 5; // defines a global variable x, with the intial value 5int square(int x) // declares a function parameter x{  int result;  // declares a local variable result  result = x * x;  // uses the local variables result and x  return result; // uses the local variable result}int cube(int x) // decalares a function paramter x, NO RELATION to the above x in square OR the global variable x{  int result;  result = x * x * x;  // uses the local variables  return result;}int square_x() // doesn't take any arguments{  return x * x; // returns the square of the global variable x, which will be 5 * 5 IF noone has changed its value before calling this function. }int square_y() // doesn't take any arguments{  return y * y; // this will not compile, there is no local or global y to call.  The y below in main cannot be seen directly by this function at all, this function can only see local variables, parameters, and global variables.}int main(){  int y = 3;  // declares a local variable y, intially set to 3  int r1;  int r2;  r1 = square(x); // uses the global x, returns 25  r2 = cube(y); // uses the local y, returns 27}


what is MEANS when a function takes a parameter is that the compiler generates code to COPY the value of the object you pass into the function during the call.

So when we say that function "square" takes 1 argument, we mean that everybody who wants to call the function must give it a value, which will be copied onto the stack so the function can operate on it. The value the function operates on is not a specific variable or location in memory, it is a specific place on the stack ... lets imagine we are on an x86 machine without optimizations, it might likely be on a place in the stack might call -4, meaning 4 bytes from the current "top" of the stack. When the compiler generates code for "square(x)" what is does is copy the value of x to the top of the stack, adjust the pointer at the top of the stack (so that x will be at -4) and then "call" the function (transfer execution to the function) ... the function does not know what the "x" in main is .. it DOES however know that it has 1 argument, which is located on the stack, so it does math on that. Then when it has computed the results of that operation, it returns its result (on x86 this usually means it copies the result value into the AX register and then transfers control back to the function which called it).

So the "x" in the function is a alias for whatever happens to be located 4 bytes from the top of the stack, when the function begins executing.
In C++, "varibles" are "typed".

"int" is a type.

The type of a variable determines a number of things about it. In many cases, it determines how much memory it takes up (bits of computer data) and how the language treats your usage of that memory.

void func(int parameter);


Above we have a function prototype. What it says is:
I am a function, my name is func.
I return nothing (void) to the caller.
I expect to be passed a copy of an int. I choose to name that copy "parameter".

So, when another function calls the above func:
int global_integer = 10;void main() {  int local_integer = 8;  func(local_integer);  func(global_integer);}


In the above code:
"global_integer" is an integer that happens to be global.
"local_integer" is an integer that happens to be local to main.

main() calls func twice. The first time it copies local_integer into the first parameter of func, the second time it copies global_integer into the first paramter of func.

This means the 'body' -- the code inside -- func is run twice. Once with a copy of the value of local_integer (8), and once with a copy of the value of global_integer (10).

Note that the names of the two ints can be almost anything -- I just named them in ways that make them describe themselves.
I have a good understanding of local and global variables, as well as an alright understanding of passing variables (Well, maybe not as good as I think).

However, I do feel that this should work.
#include <iostream>#include <conio.h>using namespace std;int addNums( int num1, int num2, int result );int main(){    int n1, n2, total;        cout << "Number 1: ";    cin >> n1;    cout << "Number 2: ";    cin >> n2;        addNums( n1, n2, total );    cout << total << endl;        getch();    return 0;}int addNums( int num1, int num2, int result ){    result = num1 + num2;    return result;}
Quote:Original post by Kenny77
I have a good understanding of local and global variables, as well as an alright understanding of passing variables (Well, maybe not as good as I think).

However, I do feel that this should work.
*** Source Snippet Removed ***

No. As NotAYakk said, you are passing a copy of total. That copy is being overwritten within your function...but because it is just a copy, the original total remains unaffected.

When you return result, that allows you to do this:
total = addnums(n1, n2, total);

That copies the new value of result into total, so the program will output what you expect.

CM
Thanks for the post CM, and I now have come to the conclusion that I am more patient then I thought, and, the code should look like this:
#include <iostream>#include <conio.h>using namespace std;int addNums( int num1, int num2t );int main(){    int n1, n2, total;        cout << "Number 1: ";    cin >> n1;    cout << "Number 2: ";    cin >> n2;        total = addNums( n1, n2 );    cout << total << endl;        getch();    return 0;}int addNums( int num1, int num2 ){    return num1 + num2;}


And of course, thank you all who helped me take another step towards creating games.

This topic is closed to new replies.

Advertisement