Help ATS with a contribution via PayPal:
learn more

Programming Lessons Part IV: Functions/Methods and Variable Scope

page: 1
0

log in

join

posted on Sep, 6 2008 @ 11:56 AM
link   
Part IV: Functions/Methods and Variable Scope
Okay, we've got some fun stuff today, especially for those with a touch of Obsessive/Compulsive Disorder. We're going to deal with functions/methods, which are simply a way of organizing your code. You've already been working with functions since day one here -- the main method is a function, as is Console.WriteLine. Today though, we're going to learn how to create our own functions. Cool, huh?

A quick note on the terminology: I'm using the terms "function" and "method" interchangeably, and for once in this series, they really are. The main difference between the two of them is simply a matter of perspective; later on, we'll start talking about something called "object-oriented programming." For now, don't worry about what that means. But, when you're doing object-oriented stuff, a function is called a method. Programmers like to do stuff like that to confuse you


Let's get started, shall we?

Functional Functionality
A function is pretty simple to start off with; here's a quick example. Find the last curly brace of your main method, hit the enter key a couple of times, and put the following code:

public static void WriteHello() {
Console.WriteLine("Hello");
}

This is a simple method, named "WriteHello", that has a single line of code that (surprise!) writes the word "Hello" to the console. When you want to call it inside of your main method, you simply call it like this:

WriteHello();

Doesn't get much easier than that, does it?

See, the cool thing about this -- why functions are so important in coding -- is that you can call it any number of times. For this example, that's pretty stupid -- you're still writing one line of code, though it might be a bit easier. But let's say you were wanting to print several lines of text to the screen, and do it multiple times:

public static void WriteStuff() {
Console.WriteLine("Hello World!");
Console.WriteLine("I'm learning how to program in C#.");
Console.WriteLine("This example is a little stupid, isn't it?");
}

Now you can simply call WriteStuff() in your code where ever you want to print those lines of code, and the compiler will take care of it for you. Neat, huh? Okay, enough with the simple stuff; let's try to throw something useful at you now:

public static int Multiply(int a, int b) {
return a * b;
}

That's a bit different, isn't it? It's still pretty straight forward though; I'll explain it. First off, ignore the "public" at the front; that's object-oriented stuff we're saving for later. Same with "static". Next, you have the keyword "int". This is the function's return type -- this is the type of the value the compiler's going to expect you to come up with when you're done with the function. (This will be a bit more apparent when we call it in a moment.) Then you have the function name, Multiply. After that, inside the parenthesis, you have what we call "parameters". These are values that are passed to the function, and they operate kinda like variables -- with a bit of a twist, that we'll cover in a little bit too. Anyways, this tells the compiler that you're expecting two int values to be passed into the function when ever someone calls it. Which will look something like this:

int firstNum = 5;
int secNum = 9;
int result = Multiply(firstNum, secNum);
Console.WriteLine("The result is " + result);

Okay, so this is a contrived example -- it'd just be easier to do a direct multiply (i.e. firstNum * secNum). But we're still crawling here -- well, maybe standing up a little bit, but we haven't really started to walk yet. Anyways...

You should have "The result is 45" printed on your console _ (If not, see me after class -- something's not kosher here...) The cool thing about functions is that you can put pretty much everything inside of them that you had been putting in your main function -- variable declarations, function calls, loops, conditionals, etc. You can return any kind of data type -- the "void" that we used as the return type above translates to "I'm just doing stuff, but I'm not returning anything," -- and take any data type as a parameter. And if that wasn't enough, you can reuse the functions as often as you like, pretty much anywhere (there's limitations on that that again we'll cover with the object-oriented programming).

Cool stuff, huh?

One quick thing with C#: you can't put a function declaration inside another function. There's some programming languages that allow this; C# isn't one of them. So if you're coming from a different programming language, keep that in mind.

Scope: Not Just Mouthwash Anymore
Now that you know about loops, conditionals, and functions, it's time to start moving away from the "look what you can do" side of coding and into the darker, "okay, here's the fine print" side. The first thing we'll discuss in this area is the concept of "variable scope." This is simply where you are and are not allowed to use a particular variable name.

The rule is really simple: look for a "{}" pair; everything within those two curly braces has a specific level of scope. Here's a quick example:

int a;
if (true) {
// a is still available
int b;
if (true) {
// a and b are both available
int c;
// a, b, and c are available here.
}
// a and b are available out here
}
// only a is available out here

Quick explanation: The variable c is only available in the inner-most if block; the variable b is available inside both if blocks, but not outside of the outer if block. The variable a is available in all locations. This would hold true if it were a function declaration as well; variables declared inside a function -- and that includes the parameters as well -- are only available inside that function. Just like c is only available within the two curly braces we declared it at. Make sense?

I mentioned above that function parameters are almost like variables, but they have a limitation. That limitation is (for our purposes, at least) because of their scope -- generally speaking, you cannot change the value of the parameter. If you do, the value stays changed inside the function call, but once the function returns, whatever you passed to it goes back to its original value. Check this out:

// put this outside the main method
public static void ChangeParam(int myParam) {
Console.WriteLine("Inside ChangeParam, before changing: " + myParam);
myParam = 3;
Console.WriteLine("Inside ChangeParam, after changing: " + myParam);
}

// put the following inside the main method
int theNumber = 12;
Console.WriteLine("theNumber before ChangeParam: " + theNumber);
ChangeParam(theNumber);
Console.WriteLine("theNumber after ChangeParam: " + theNumber);

When you run it, you'll see that the value you pass to the function does change inside of the function, but not when it returns. (As an aside, there's instances later on where this rule doesn't apply, or it doesn't apply as much as you'd think it does. For now, just consider it the gospel.)

Alright, I hope that made some kind of sense. As it stands now, you're pretty well geared to handle a lot of programming tasks; maybe later on I'll try to come up with homework for you


As always, feel free to ask any questions you may have, or post any suggestions or comments. Catch you in the next installment.






new topics
 
0

log in

join