Monday, March 28, 2011

learn c sharp Gaming Chapter 5


Short-Circuit Evaluation
Let me go off on a tangent here and go over a topic that is fairly important when evaluating
conditional statements.
All C-based languages support something called short-circuit evaluation. This is a very
helpful performance tool, but it can cause some problems for you if you want to perform
some fancy code tricks.
If you know your binary math rules, then you know that with an and statement, if either
one of the operands is false, then the entire thing is false. Table 2.7 lists the logical and and
logical or result tables.
Look at the table, specifically the two lines where x is false. For the operation “x and y,” it
doesn’t matter what y is because the result is always going to be false. Likewise, if you look
at the first two lines, you’ll notice that whenever x is true, the operation “x or y” is true,
no matter what y is.
Table 2.7 Logical and/Logical or result tables
x y x and y x or y
true true true true
true false false true
false true false true
false false false false
So if you have code that looks like this:
if( x && y )
the computer will evaluate x, and if x is false, then it won’t even bother to evaluate y.
Likewise:
if( x || y )
If x turns out to be true, then y isn’t even evaluated. This is a small optimization that can
speed up your programs greatly in the right circumstances. For example:
if( x || ( ( a && b ) && ( c || d ) ) )
If this code executes and finds out that x is true, then the whole mess on the right side will
never be calculated at all.
This can be a very tricky source of bugs, but only if you write tricky-looking code. Look
at this line, for example:
if( x || ( ( y = z ) == 10 ) )
If your first reaction to seeing this code is “What the hell is going on here?” then you
deserve a cookie. This code is unbelievably ugly, and you can’t tell what the author intended
to do with it. But unfortunately, this is perfectly legal C# code, and someone somewhere
will think they’re hot enough to write stuff like this and get away with it.
Anyway, if x is true, then the computer ignores the second half of the code. But if x is false,
then whatever is in z is assigned to y, then the result is compared to 10, giving this code
the same structure as this more readable version:
if( x == false )
y = z;
if( x || ( y == 10 ) )
The second version looks almost nothing like the first, so you can see how trying to do
some clever tricks will get you into loads of trouble one day.
Looping
The third trait a computer language has is repetition, or looping. Essentially, looping allows
you to perform one specific task over and over again. C# has four looping mechanisms
built-in; the three I’ll cover in this section are inherited from the C programming language.
I won’t get to the fourth one until Chapter 4, “Advanced C#.”
Looping 27
while Loops
The first and easiest loop structure is the while loop. Here’s an example:
while( x < 10 )
{
// do stuff
}
Whatever is inside the brackets will be executed over and over until the value of x is less
than 10. If x never gets to be equal or above 10, then the loop will loop infinitely.

for Loops
Another popular loop is the for loop, which is just a different way to perform a while loop.
The basic syntax of a for loop is as follows:
for( initialization; condition; action )
The initialization part of the code is executed only once, when the for loop is entered. This
allows you to set up any variables you might need to use.
The condition part is evaluated at the beginning of each loop; and if it returns false, then
the loop exits.
The action part is executed at the end of every loop.
Generally, you use for loops to create a loop that will go through a range of numbers for
a particular variable. For example, if you want to perform 10 calculations on x, where x
ranges from 0 to 9, you would create a loop like this:
for( int x = 0; x < 10; x++ )
{
// do stuff
}
The first time the loop executes, x is 0, and then the next time it is 1, and so on, until it
reaches 9.
You can also do some other fancy stuff, like initialize multiple variables or perform multiple
actions:
for( int x = 0, int y = 0; x < 10; x++, y += 2 )
This loop creates two variables, x and y, where x loops from 0 to 9, and y loops from 0 to
18 by skipping every other number.
28
do-while Loops
Sometimes in programming, a situation will arise in which you want to make absolutely
certain that a loop executes at least once. Look at this code, for example:
int x = 0;
while( x > 0 )
{
// this loop never gets executed
}
With for loops and while loops, there’s always a chance that, if the condition evaluates to
false, the code inside the loop will never be executed. Instead of a for loop or a while loop,
you can use the do-while loop, which executes everything and checks the condition after
the loop is executed. Here’s an example:
do
{
// loop code here
} while( condition );
Break and Continue
break and continue are two useful keywords that you can use when doing stuff inside of
loops to alter their flow.
Break
The first is the break keyword, which you’ve already seen used inside of switch blocks.
Basically, putting in a break will cause the program to jump to the end of the loop and
exit. Here’s an example:
for( int x = 0; x < 10; x++ )
{
if( x == 3 )
break;
}
This loop will make x go through values 0, 1, 2, and 3, and then quit out when x is 3.
Continue
The other loop modifier is the continue keyword. This keyword causes the loop to stop
executing and go back up to the top and start over. Here’s an example:
for( int x = 0; x < 10; x++ )
{
FunctionA();
Looping 29
if( x == 3 )
continue; // jump back up to top, skip anything below
FunctionB();
}
Pretend that FunctionA and FunctionB actually exist for a moment. This loop will make x go
through every number from 0 to 9. On every single iteration, FunctionA will be executed, but
when x is 3, the code will skip FunctionB() and jump right up to the top of the loop again.
Scoping
The term scope, when dealing with a computer program, refers to the place in a program
where a variable is valid. For example, say you have this code in a program:
class ScopeDemo
{
static void Main( string[] args )
{ // bracket A
int x = 10;
} // bracket B
static void blah()
{
// x = 20; <—- YOU CAN’T DO THIS!
}
}
The variable x is said to have a scope between brackets A and B. If you tried referencing x
outside of those brackets, the C# compiler will give you a strange look and ask you what
the hell you’re talking about.
Seems simple enough, doesn’t it? Here’s another example:
static void Main(string[] args)
{
if( 2 == 2 )
{ // bracket A
int y;
} // bracket B
// y = 10; <—- YOU CAN’T DO THIS!
}
The if block in this code will always execute because 2 is, obviously, always equal to 2; but
that’s beside the point. Inside of brackets A and B, a new variable, y, is created, and then
the if block ends. But y only has a scope in between those two brackets, meaning that
nothing outside of the brackets can access it; so if you try using y outside of the if block,
the computer will barf error messages all over you because it has no idea what y actually is.
There’s still one more example I’d like to show you:
static void Main(string[] args)
{
for( int x = 0; x < 10; x++ )
{
// do something here
}
// x = 10; <—- YOU CAN’T DO THIS!
}
In this final example, you’ve created a new variable x inside the for statement, and you can
access x anywhere inside the parentheses or the for block, but nowhere outside of it.
Summary
Computer languages are very complex, and no one can ever fully understand an entire
language anymore—they’re just far too complex nowadays. Luckily, you won’t need many
of the features in a language, so you don’t have to be a versed expert in the language in
order to use it—that’s what reference manuals are for.
This chapter is enough to get you started on making some simple C# programs, but you
really can’t do anything really complex yet. But that’s okay; you’re only two chapters into
the book!
This chapter has shown you how to create your very first C# program and compile it, and
has introduced you to the very basic concepts of the language, such as the basic data types,
mathematical operators, conditional statements, and looping statements. In the next
chapter you’ll go on to even more advanced topics.
What You Learned
The main concepts that you should have picked up from this chapter are:
_ How to compile and run a C# program.
_ Every program has a main class that defines an entry point, where program execution
starts.
_ There are many built-in numeric data types in C#.
_ Short-circuit evaluation can be used to speed up your programs, but may introduce
unforeseen flaws.
_ Constants make your programs easier to read.
_ Typecasts are strict in C# when compared to C/C++, because you might accidentally
lose data if you’re not paying close enough attention.
_ Scoping allows you to manage your variables in an efficient manner.

No comments:

Post a Comment

Your comment is pending for approval

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...