L34rn teh C++ Lesson 4

Cunbelin

Newbie
Joined
Aug 3, 2003
Messages
281
Reaction score
0
Alright here we go number 4

Lesson 4
TEH PA1N! NO MOR!

Alright now it is time to introduce a totally new concept, the code we made before quite frankly was so awful, I'm waiting for a lightning bolt to strike me for writing it. So we are going to learn how to clean that code up. The first way we are going to do that is with a new command, the switch statement. Basically it does all that if/else/if/else/if/else crap for us. Lets take a look at a simple version of a switch statement:

PHP:
#include <iostream.h> //still need it

int main ()
{
	char a_char; //lets change this up a bit
	cout << "please enter A, B, or C\n>";//same old same old
	cin >> a_char; // get that character
	switch(a_char)//looks kind of like an if statement
	{
		case 'A'://this is the actual testing part
		{
			cout << "You hit A, you win!";
			break;
		}
		case 'B'://and here is another test
		{
			cout << "You hit B, you win!";
			break;
		}
		case 'C'://and another
		{
			cout << "You hit C, you win!";
			break;
		}
		default ://and this is the, big suprise, default kind of like that last else
		{
			cout << "Bad Human!";
			break;
		}
	}
	return 0;
}

Ok so now we've seen the switch statement, lets talk about it, simply put, it is a really odd thing in that it doesn't fit syntactically with the rest of the language. So we are going to accept it simply as the oddity that it is and learn how to use it. Basically what happens is we give the switch statement a variable, and it compares it to each case, if it matches a case, any code between the matching case and a break is executed. In other words, we can make this even simpler:

PHP:
#include <iostream.h> //still need it

int main ()
{
	char a_char; //lets change this up a bit
	cout << "please enter A, B, or C\n>";//same old same old
	cin >> a_char; // get that character
	switch(a_char)//looks kind of like an if statement
	{
		case 'A'://ok so if a_char matches 'A' we execute until we hit a break
		case 'B'://if A did not match A but B did match the same thing happens
		case 'C'://and the same for C
		{
			cout << "Good Human"; //we lose the specific message, but we gain simple code
			break;//and now we return to outside the switch statement.
		}
		default ://and this is the, big suprise, default kind of like that last else
		{
			cout << "Bad Human!";
			break;
		}
	}
	return 0;
}

So a switch statement takes a variable, and looks for a matched case, when it finds a matched case it executes all code until it hits a 'break;', for example if we took out the 'break;' after 'cout << "Good Human";' we would have both "Good Human", and "Bad Human" printed. There is something else you should know about switch statements, but before I talk about that, I have to talk about what a constant is compared to a variable. Seems pretty straight forward a constant is well cosntant, and a variable, changes, and that is pretty much it. C++ uses both variables and constants, and in fact you have already used both of these. OMG WTF WEHN DID 1 UZE KONSTNTZ!?!?! any time you use a number like 7 in code that is a constant, or when you use a character like 'a' that is a constant. Now back to switch statements, there are two restrictions on cases, one is that they have to match the type of the variable, and two is that they have to be a constant. That means no comparing with variables.

Alright enough about switch statements for now, we have to get through a much bigger concept today, and that is the concept of functions. There's a saying, about this I'm sure, but basically the idea of functions stems from the idea that you shouldn't have to do something you have already done again just because you want to use it again. It's like a game, you shouldn't have to install and set it up each time you want to play it right ? So the idea of functions is that you shouldn't have to re-write code every time you want to use it. The way you used to do this in older langauges was to use a command called goto, and because every line in the code was numbered, you could use goto to go to a particular line in the code, and so you could reuse code, in whole or part. The problem was if you had to change something and add in a line, all of a sudden all of your goto's didn't work. Not to mention as time goes on and thing got more and more complex you would have ridiculous amounts of goto commands. Thankfully we will never have to use a goto in C++ because of functions.


Now before we get into this more, I want you to try a difficult concept, remember the warehouse(RAM), remember how it had all the boxes(bytes) to put stuff(data) in, and that what a variable really is, is the location of the first box and how many boxes it takes up? Well think of this, all of your variables are stored in boxes too, in fact all of your code is stored in a boxes as well! Not only that but it is stored in the same order as you write it, so if we could somehow make a variable that has the codes address, and the size of the code, we could use that variable to call the code over and over again. If you don't get that it's ok, hell I've been programming for a while and starting to think about it too hard still blows my mind. So that variable that has address and size of the code, is what we call a function, Only problem with it is that code on it's own doesn't do much, we need to have variables, that isn't a problem, but if we want to reuse the code we have to be able to use different variables. This all combines to make functions a little more complex in their declarations and definitions. Lets take a look at the anatomy of a function declaration:

return_type name (arguments);

Ok so what does this mean, well remember I mentioned needing to give it different variables, those are the arguments, you can have as many arguments as you want, these are the variables that the function needs to work. return_type allows you to decide what happens when your function is evaluated (much like the operators when evaluated functions return something). This is probably making little sense, but lets press on to a function definition:

return_type name (arguments)
{
code;
return;
}

look familiar ? kind of like our main block, in point in fact main is indeed a function, and we have been defining that function in each of our bits of code. You may note that main has never had any arguments, and you would be half right, in C++ whenever there is a () with nothing in it, it is assumed to contain a variable type void, void can also read as zero, or none, and in the case of main we had no arguments so we marked it as void by our non-marking. We also have ended with a return statement, this statement works similar to the break statement but we can attach a value to it, in the case of the main function we have always attached 0 to it. the value attached to the return is what the function evaluates to.

Ok now there is one more thing we need to cover about functions before we try and use one, and that is that we have to be able to actually USE or "call" them, to do this we use a function call, it looks like this:

function_name (passed_arguments);

Ok so heres how this goes, we are calling the function "function_name" and we are passing it the variable "passed_arguments", to the function, then whatever code is stored in the function is executed, using the value of "passed_arguments". To note passed_arguments doesn't have to be a variable, it could also be a constant (remember 1, 2, 3, or 'a', 'b', 'c').

Ok so still not making any sense ? lets take a look at a full function declaration, definition, and we are going to call a function (inside our main function)

PHP:
#include <iostream.h>

int func (int arg);//OMG WUT IZ DIZ! IT IZ A DEKLARSHIN!

int main ()
{
	int an_int;
	an_int = 7;
	func (an_int); //OMG A FUNKSHIN CALL!
	func (6);	//not one but two!
	func (4 + 1);	//three !
	func (2 * 2);	//FOUR!
	func (an_int - 4);//YOU ARE MAD MAN! 5 function calls!
	func (9 - an_int);//6!, you truly are insane
	func(func(1));//7, and 8 counting the nested one!
	return 0;
}

int func (int arg) //so we have the return type (int) the name, and then we have the variable that takes in
{		   //passed arguments whatever they may be.
	cout << arg; //we are defining the function here
	cout << "\n";//that is what the function will do
	return 0;//this looks like main.
}

Alright, well run the code, go ahead and try it. I was a little evil there, I added a whole bunch of concepts there without telling you, basically I put statements that have to be evaluated into the place where passed arguments go, lets talk about that for a second, basically what happens here, is whatever is in the parentheses is evaluated first, and then it is passed to the function, so in our first few cases, the operators are used to modify the numbers, in our last case we have a function in there, and remember functions are evaluated just like statements, so it works the same way.

Ok on the next page we are going to clean up our calculator program by using functions and the switch statement, if you would like you could try doing this on your own before looking at my solution.
 
Ok I think we are going to wrap up for today by re-doing our calculator with functions. The first thing to do here is to identify the functions we need. Now in this case we mostly want to simplify our code and make it nicer looking, to do this we are going to make three functions, one for adding, one for subtracting, and one for multplying, we will also rework the if/else crap to a switch statement:

PHP:
#include <iostream.h>

int add (int first, int second);//we need two numbers here so that we can do our work
int subtract (int first, int second);//to do two arguments we seperate them with a comma
int multiply (int first, int second);


int main ()
{
	int first_number; //here is where we put the first number input
	int second_number; //the second number goes here
	char option; //this will hold what option the user chooses
	cout << "Please choose a mode (+, -, *)\n>";
	cin >> option;
	cout << "Please enter the first number\n>";
	cin >> first_number;
	cout << "Please enter the second number\n>";
	cin >> second_number;
	switch(option)
	{
		case '+':
		{
			cout << add(first_number, second_number);
			break;
		}
		case '-':
		{
			cout << subtract(first_number, second_number);
			break;
		}
		case '*':
		{
			cout << multiply(first_number, second_number);
			break;
		}
		default :
		{
			cout << "You didn't enter a +, -, or *";
			break;
		}
	}
	return 0;
}

int add (int first, int second)
{
	return (first + second);
}

int subtract (int first, int second)
{
	return (first - second);
}

int multiply (int first, int second)
{
	return (first * second);
}

Well now that gives us a bit more to chew on, first off we use the evaluation rule all around, and with a little reorganizing we basically halved the size of the code, We also introduced multiple arguments for functions, you could keep on listing as many arguments as you like as long as they match in the definition. Alright tomorrow we are going to introduce the concept of loops and also talk more about functions, and we'll be adding division to the calculator!
 
You use { } in case? That seems wrong... But as I said in the other thread, I'm as rusty as a nail that has been on the bottom of the ocean for 1000 years :)
 
Technically it isn't needed, but I personally find that it makes the extremely odd structure of the switch statement less confusing. To note you also don't have to name arguments in function declaration, but I find it good policy, also there were some if statements in the last lesson that I would have done as if(bar) foo; rather than use curly braces, but again for readability and simplicity of syntax I am making sacrafices.

Basically there is no reason not to do these things, they all lead to what I see as cleaner looking code, that is easier to read, and presents a more consistent style than what is normally allowed in C++. I mean you don't have to put spaces on either side of binary operators, though it was included in the orginal C spec and looks nicer. Also I'm drawing from my experience, to show what has worked for me, though I expect people will encounter different coding styles as they go along.
 
he doesn't need to use the {} in case as long as he doesn't have more than one function or what so ever to be executet in the specific case.

here you're gonna need them:

case WM_COMMAND:
switch(LOWORD(wParam))
{
case ID_FILE_OPEN:
DoFileOpen(hwnd);
break;
case ID_FILE_SAVEAS:
DoFileSave(hwnd);
break;
case ID_EDIT_CUT:
SendDlgItemMessage(hwnd, IDC_CHILD_EDIT, WM_CUT, 0, 0);
break;
case ID_EDIT_COPY:
SendDlgItemMessage(hwnd, IDC_CHILD_EDIT, WM_COPY, 0, 0);
break;
case ID_EDIT_PASTE:
SendDlgItemMessage(hwnd, IDC_CHILD_EDIT, WM_PASTE, 0, 0);
break;
}
break;


or here:

case WM_CREATE:
{
HWND hTool;
TBBUTTON tbb[3];
TBADDBITMAP tbab;

/* ....
....*/

}


that's a part of the window procedure for a MDI application

<edit> heh, now i learned something "new". i am pretty rusty, and the function was something i forgot ;)
 
I always learn the shortest thing first :)
But true, its better to have as clean code as possible... Though it IS funny to use a single line :)

Sidenote: That green is still VERY hard to see against the darker grey (second post)
 
The function prototypes at the top aren't needed, but if you omit them then you have to move all the function declarations (add, multiply and subtract) above the main() function (they have to be defined before they are called - otherwise the compiler will give an error).
 
Originally posted by Nith Sahor
The function prototypes at the top aren't needed, but if you omit them then you have to move all the function declarations (add, multiply and subtract) above the main() function (they have to be defined before they are called - otherwise the compiler will give an error).
Its good to have them there to keep track of them. See it as an index :)
 
also worth mentioning that without the break command in each case, it will fall through to the next case unless there is one (a break)

switch(number)

case '1':
{
cout<<"you picked one";
}

case '2':
{
cout<<"even if you entered 1, this message will show up because there was no break command at the end of case 1";
break;
}

case 'default'
{
cout<<"ok, im done." ;
break;
}
 
Yeah I mentioned that you fall through without a break, but I didn't give a huge example of it.

I know the green is bad, but as far as I know the only way to allow for proper tabbing on the forum is to use the PHP tag and it decides the colors for me. From now on if I have to split the posts I will add in an intermittent post so it goes back to the light grey.
 
i think its great that youre doing this, although ive learned almost nothing yet (i know quite a bit of java, but want to learn c++ because of future mod making / game making plans)! keep up the good work!
 
heh well if you have the concepts of Java already, and I mean truly understand how it works, transitioning to C++ isn't that hard. In truth we haven't even gone outside of C functionality at this point, and unfortunately we can't until we finish up a few more concepts (namely arrays and pointers, and probably structures.) Once we get there we can start talking about objects, and messaging.
 
uhh yah, this thread is probably really old, but i have a question about break;...im a newb programmer and my compiler (bloodshed dev c++) does not seem to recognize breaks how you have them in the code, or at all for that matter. What is up with this?
 
OK...oopps...I have no idea why they were not working bot now they are so disregard my above post please ;)
 
Back
Top