Introduction to programming in C, C++ and WIN32
- Orange_Newton posted this article Tuesday, 06 December 2005
C is a programming language of older date, although there are many that are older. The myth says that it originated as a joke, but as it quickly became popular it was too late to stop it. It actually became so popular that it held back the development of object oriented programming languages, people were simply not willing to change away from the C language. At first the problem was solved by C with classes but that language never really made it very far. Another solution was C++ developed by the Dane Bjarne Stroustrup it did what C with classes could not, it extended the C language without destroying the foundation. Even today it is easily possible to make C programs and compile them in a C++ compiler. In addition to C, C++ contains a lot of small extensions most importantly are probably the classes, instances of a class is normally called objects. Thus C++ is an object oriented programming language, but not in the same sense as Java where EVERYTHING is classes and objects. I wonít mention J*** anymore (even though I know I will have to recognize the existence of this frightening language). Nope not done yet, now it is time to bore you with WIN32, to understand WIN32 we must look back in time and understand how it all began (no not big bang, although that would probably be a lot more interesting). We will begin with the 8086 CPU architecture, in the beginning CPUs were constructed with 16 bits, this were adequate for a 16 bit OS like DOS, an old command based OS that was quite stable compared to many modern OS, however graphically it wasnít that useful. So a change came as the 8086 CPU got GUIs or more precisely it got a WIMP GUI, known as Windows, in the beginning these were nicely numbered until 3.11 now the users began demanding more speed, one of the problems with that was that 16 bit simply wasnít enough for big calculations so the 32 bit CPU was born, this meant that a new OS was needed too and this is where Windows 95 the first WIN32 OS this also led to an increase in graphical GUI and after some time companies began making programs that only started in Windows 95 or newer. Today many of those programs are outdated, as more recent versions of Windows has been developed. At the time of writing the newest are those on the NT platform like NT, 2000 and XP. This concludes the history lesson for today. You might think that this was just a long boring story and I agree with you totally, it was merely a test to see if you were smart enough to skip it or determined enough to read through it and thus proving that you are ready to learn to make programs.
--- End of boring probably wrong history junk. ---

--- Start totally correct programming stuff ---
Requirements: If you were smart enough to skip first part or determined enough to read through it you are probably ready for the rest of this thing. Be warned that this is a VERY short introduction.
You should be able to understand that programming lines are read sequentially by the computer meaning that line 1 gets performed before line 2 and line 3 gets performed after this and so forth. (if that does not make sense to you Iím sorry that I have misjudged you and I urge you not to continue to learn programming you would be wasting your time).

It would be a great idea to have a compiler at hand for this and any future tutorials on programming, I recommend the free compiler Dev-C++, or the very expensive Microsoft Visual Studio (yes it is better but it is NOT worth THAT MUCH),  every example I make I test in Dev-C++ they SHOULD work in VS too but I wonít guarantee it (if I know something is different I will mention it). I wonít test in VS since I donít expect people who are just learning C++ to buy an expensive compiler. One of the reasons VS is better than Dev-C++ is that it shows the contents of classes when you type Ď->í or Ď.í , that option can be enabled in Dev-C++ however my experience is that it is unstable in the current beta version. I will mention Watcom as an alternative to VS, it is a professional compiler, however it lacks a GUI and is quite hard to use, and thus I donít recommend it to beginners. If you decide to use Watcom anyway you are probably better off without a tutorial in C++ and WIN32 and you will at least have the know-how to change the examples so that they work in Watcom.

Lets start with something simple, variables are important and quite basic, variables is what holds the data that your program uses. Imagine a database with persons in it, a bank database or something like that. We want to register data about these persons, at first we start out with 1 person, later we will learn to make an almost unlimited big database. What type of info do we want about a person? An age would be nice, age is usually represented with an integer value (for the non native English speakers thatís 0,1,2,-3 and so on) we could restrict it to positive integers but for now we accept integer, integer is called int in C (lucky for those native English speakers). We also want to record their sex, we could do this with letters like Ďfí or Ďmí for female or male, that would take a character or char as they are known in C. But since we only want those 2 possibilities we might as well use a bit known as a boolean (just to catch people of guard), we call the boolean male and set it to 1(true) if it is a male and 0(or false) if it is a female. We might also want to record their current balance on the account we could do that with an int and just record it in cents, but since we are just learning we will use a floating point value known as float in C. One important thing would of course be name. However that works a bit differently than the others, since name does not necessarily have a max length in bytes. Each letter of a string is a char so if we had an array of letters we could make strings and use those as names the basics of arrays are however beyond the scope of this tutorial so I will just show how to use the array to hold a string like a name. Time for an example, becourse it is the first I will explain each line very carefully.

001   #include <string.h>
003   int main(int argc,char **argv){
004    char name[256];
005    int age;
006    bool male;
007    float money;
009    strcpy(name,"Bob");
010    age=42;
011    male=1;
012    money=11.50;
013    return 0;
014   }

The numbers in front are not part of the code, they are only there so that you donít have to count manually.

line 01; the program needs a library to work with strings, these will be explained in another tutorial.
line 03; the magic beginning code of the C program its weird appearance will be explained in a latter tutorial.
line 04; in C and C++ it is necessary to tell the computer the name and type of variables that we use latter on. This line tells the compiler that it is an array of characters that has at most 256 characters, this means that we can hold names that are at most 255 letters long the reason that we lose 1 is because the computer has to know where the name ends and that is represented with a 0 (not the character Ď0í), this is not a problem since Bob is less that 255 letters long. Also notice that almost every line  ends with a ; this symbolizes the end of a sentence in C and C++ and at times it gets very frustrating looking for errors when all you forgot was a ; (If you read the error messages it says you are missing a Ď;í before line ## that generally is quite helpful when figuring out why it doesnít work.)
line 05; more declaration of variables age is an integer or int, age is the name like name was the name of the name variable (say that 5 times very fast :-)).
line 06; as I already explained we call the sex male and set that to true or false. In C and C++ that is equivalent of 1 and 0 and thus I will mostly use these since they are shorter (acutely anything that isnít 0 is true in C and C++)
line 07; a float for the money poor Bob is almost broke, normally it would be smarter to use an int and write it in cents simply dividing by 100 when dollars were the expected type, this would prevent stuff like Bob having a half cent. Another advantage would be that integer calculations are a lot faster, but thatís no longer a valid argument since modern computers are so fast that you would need MANY to feel any difference.
line 09; since we are done declaring variables we want to specify their values since name is a string we need to use a function from the string library, functions and arrays will be explained in other tutorials.
line 10-12; these arenít strictly mathematically correct, however that is the way you copy values into variables in C and C++. 42 gets copied to age, 1(true) to male, and 11.50 to money.
line 13; return 0; terminates the program and tells the OS that it was successful (not that useful unless you have a script or something that needs the info), example of how the code should be done in WIN32 will follow shortly.
Line 14; the } belongs to the one from line 3 it tells the compiler that this is the official ending of the function main.

That wasnít so bad, was it? But I did promise to translate it to proper WIN32 code. If you have heard others say that WIN32 code is a huge step from standard dos code that would probably surprise you, however I disagree with that statement and thus I jump directly to WIN32 now. (if you find that you agree with the above statement after reading the code there are PLENTY of other tutorials for you, but mine are probably a bad idea sorry).
If you are still reading and havenít just ripped of 2/3 of your hair in frustration it is totally safe to read on (if you have ripped of 2/3 of your hair you are quite desperate to learn).
I will repeat the same example as above and explain the lines Iíve changed.

001   #include <windows.h>
003   int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow){
004   char name[256];
005    int age;
006    bool male;
007    float money;
009    strcpy(name,"Bob");
010    age=42;
011    male=1;
012    money=11.50;
013    return 0;
014   }

If it wonít compile itís probably because you need to start a WIN32 project (not console) go to files and create a new project. (You should be able to figure out how to do that on your own). Delete the contents of the auto generated main file, and use mine instead (mine is a lot smaller). Remember to remove the line numbers and compile it(in Dev-C++ thatís the button that looks like a windows logo that has been disassembled (thatís NOT what it is SUPPOSED to look like, but it is the best description I can come up with)). The run button is the one next to it, and then theres the compile and run (the one you will use the most). In VS there is a play button that compiles and runs the project.

line 01; I have exchanged the string library with the windows library. I didnít really have to, but it looks nicer when the rest is windows stuff.
line  03; main is replaced by WinMain and the magic line has grown quite long, but since it is still just a function opening thatís not a difference you will notice (unless you decide to remember it and not just copy-paste it).
Thatís it Iíve changed nothing else, if you think that is a lot harder youíre trying to hard to remember the parts you are supposed to copy-paste in the first 1 million programs you make. You might notice that nothing happens when you start the program, thatís because we have yet to tell it to make some output, I will not explain how to do that in console but in Windows we use windows at first these will be simple message boxes but later on they will become sophisticated windows with menus, text fields and custom buttons (and much more). But that is getting a little ahead of ourselves even beyond the scope of this tutorial, however programs arenít that fun without output so I will explain the MessageBox function from the windows.h library. MessageBox expects some arguments one that tells what window it belongs to and one that tells it what the text should say, thereís one for the caption and then thereís one for the type (error message, information, ok butten, yes and no button etc.). We will simply use a MessageBox with an ok button and nothing else for now. For instance:
MessageBox(0,ĒIím still a total N00BĒ,ĒHallo World!Ē,MB_OK);
Try putting it in your program and see what happens, as expected it creates a MessageBox.

Lets have some fun and try the line:
MessageBox(0,ĒIím still a total N00BĒ,name,MB_OK);

If you guessed what changed it shows that your paying attention to details, if you forgot that it should be below the strcpy(name,ĒBobĒ); line and thus got an error and you based on that guessed what it did thatís still a bit impressive, and it shows that you are thinking in the correct way. But this isnít really enough is it? It would be a lot cooler if the program told us what it knows about Bob. Something like this perhaps:

There is one small problem however, the information has to be in a string, since it isnít we will have to learn about if sentences, and if sentence is a way to alter the flow of the program, we can ask if something is true and tell the computer that it should do something if it is true and something else if itís false. If sentences are made by writing ďif(ď condition goes here ď)Ē  and the following line will only be executed if the condition is true, there should not be a Ď;í after if instead the sentence that you want to be executed if the condition is true is ended with a Ď;í the line following if is usually pushed two spaces or one tabulator in to indicate that it belongs to the if, this is purely for readability, the compiler doesnít care the line after the line that follows the if can be an ďelseĒ line if it says else that means that the line after else will only be executed if the one after if wasnít. The condition is written like age==17 notice that there are two Ď=í otherwise it would be an assignment of 17 to age, and 17 is always true so that would be bad. Now we need a way to convert numbers to strings, for that purpose we use sprintf from stdio.h (or wsprintf from windows.h but that one lacks the floating point stuff so we will use sprintf for now), sprintf expects some arguments too, the first is a string that it can write to the second is a string telling what the format for the first string should look like, and the rest are the variables needed along the way. We will make a string called output of length 512, we will the use it as the first argument, next argument will be a string, strings are always represented with a pair of Ē around them. In this second string you can write %d and that means take the next argument in the function call and insert it as a integer here, %f is for the floating point value and %s for a string, it is important that the rest follows in the correct order if it says %d first the first argument after the format string should be an int etc. and now all we have to do is try it out.
001   #include <windows.h>
002   #include <stdio.h>
004   int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow){
005    char output[512];
006    char name[256];
007    int age;
008    bool male;
009    float money;
011    strcpy(name,"Bob");
012    age=42;
013    male=1;
014    money=11.50;
016    if(male)
017      sprintf(output,"Age: %d\nSex: Male\nmoney: %f",age,money);
018    else
019      sprintf(output,"Age: %d\nSex: Female\nmoney: %f",age,money);
021    MessageBox(0,output,name,MB_OK);
022    return 0;
023   }

line 5; we make the output string.
line 16-19; this is the if sentence with the condition male, if male is true, then we use the male version if male is false we use the female version.
You should now notice that something is wrong, it prints far to many decimals instead of the 2 that we want, we can correct this by changing the %f to %.2f this will tell it to print 2 decimals only, also it takes far to much writing to have both a female and male version and if you had to change the you would have to change it in both places, the solution is the conditional operator ď?:Ē it uses the syntax ďcondition?true_part:false_part so we could simply use:
sprintf(output,"Age: %d\nSex: %s\nmoney: %.2f",age,male?"Male":"Female",money);
This will make a MessageBox exactly like the one in the picture. The advantage of using the conditional operator here is clear, there is no longer a need for 2 almost identical lines and it is only a slightly more complex line.

Instead of deleting the old code (you might later discover a reason for it to be better (faster or more changes needed than just a word)), you can out comment it i.e. transform it into a comment, comments in  C start with /* and end with */ everything in between is not read by the compiler in C++ there is an additional comment type starting with // it ends with the line and is useful because you can quickly add it on a single line or behind a single line. Comments are good in that they help you when someone in the future has to read your code, it might be someone without your brilliant genius brain and total recall memory so make them short and useful. Also donít overdo it, anything learned in this tutorial like basic assignments donít need a comment, however sometimes they are useful on the declaration of variables if it isnít obvious from its name what it does.
001   ////////////////////////////////////////////////////
002   // Program: Tutorial 1 - intro
003   // Author: Allan A. Olsen AKA. Orange_Newton
004   // Date: 19-05-2006
005   ////////////////////////////////////////////////////
007   #include <windows.h>
008   #include <stdio.h>
010   int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow){
011    char output[512];    //output is used for the MessageBox content
012    char name[256];      //the name of the person used as MessageBox caption
013    int age;              //the age of the person
014    bool male;            //true if it is a male false if it is a female
015    float money;          //persons bank ballance
017    strcpy(name,"Bob");  //sets the name to Bob
018    age=42;              //Bob is 42 years old
019    male=1;              //Bob is a male
020    money=11.50;          //Bob has 11.50$ in the bank
022    // Here we make the contents of the MessageBox
023   /* //old version
024    if(male)
025      sprintf(output,"Age: %d\nSex: Male\nmoney: %f",age,money);
026    else
027      sprintf(output,"Age: %d\nSex: Female\nmoney: %f",age,money);
028   */
030    //fast version
031   //  sprintf(output,"Age: %d\nSex: %s\nmoney: %.2f",age,male?"Male":"Female",money);
033    //new version
034    sprintf(output,"%s is a %d year old %s, with %.2f$ in the bank.",name,age,male?"male":"female",money);
036    MessageBox(0,output,name,MB_OK);//we show the MessageBox
037    return 0;
038   }

As you can see Iíve plastered it with WAY too many comments using both the old type and the new type, also Iíve changed the final output to nice text instead of cold facts. This concludes the first of my tutorials, if you have any questions write me at:
The source can be downloaded here. - Allan Asp Olsen & Daniel A un dal.
OBS: Du har begrśnset adgang til siden.