0 Introduction 1, Course Syllabus 2, Part two lesson six: Creating your own Variable Type 3, part two, seventh trailer: Document Reading and writing course outline our courses are divided into four parts, each of which will have exercises at the end and will announce the answers. will also bring you in C language to write three games. Basic knowledge of C language programming what is programming? 工欲善其事, its prerequisite, the world of your first program variable. Conditional expression Loop Statement Combat: The first C-language mini-game function exercises: perfecting the first C language Games C Advanced Technology modular programming attack pointer, C language Ace Array string preprocessing create your own variable type file read/write dynamic assignment: "Hanging villain" game safe text input exercises: Interpreting pointers in your own language using the C-based SDL library Development 2D Game installation SDL Create window and canvas display image event handling: " Super Marie Push Box "game Mastering Time Use Sdl_ttf edit text with Fmod control sound combat: Visualize sound spectrum exercises data structure list heap, stack and queue hash table exercises Part Two lesson six: Creating your own variable types well-known, C is a process-oriented programming language, is different from object-oriented programming languages such as java,c#. In object-oriented programming languages, there is the concept of class. C does not have such a "type" of class, but C cannot emulate "object-oriented" programming? No, as long as you design well, C can also simulate object-oriented programming. In this lesson, we learned that knowledge about structs (structs) gives you the ability to implement object-oriented in C language. Before we learned pointers, arrays, strings and preprocessing, mastering this knowledge your C language level has been good, but how could we stop there. C also allows us to do something more powerful: Create your own variable type. We can call it a "custom variable type" and we'll look at three kinds: struct,union and enum. Because when you need to write a program that is more complex, you will find it important to create custom variable types. Fortunately, this is not particularly difficult to learn. But we need to concentrate on this lesson, because we will always use the struct from the next lesson. Define a struct what is a struct, first of all it is a shorthand for English structure (structure). So the professional term for structs is "struct". Definition: A struct is a collection of a series of variables, but these variables can be of different types. This definition is not to arouse everyone to our old friend: the memory of the array ah. Each member of the array must be of the same type, in contrast to a struct that is more flexible. In general, we are accustomed to defining structs in the. h header file, which is the group of guys with pre-processing commands and function prototypes. A STR is given belowUCT Example: struct the name of your struct {char variable1;short variable2;int othervariable;double numberdecimal;}; You can see that the definition of a struct starts with a keyword struct, followed by the name of your custom struct (such as Dog,cat,person, etc.). In general, in my code, the naming of my struct is also in accordance with the variable naming rules, only a bit different, is the name of the struct I will capitalize the first letter, for example: Schoolname. But my normal variable is usually the first letter lowercase, for example: Studentnumber. It's just a personal habit, it's easy to differentiate between common variables and custom variables in your code, and then you'll learn about the enum and union, and I'm also used to capitalizing the first letter of its name. After the struct's name, we need to write a pair of curly braces, where you put the various types of variables that your struct will contain. In general, there is at least two variables defined in the curly braces of a struct, and if there is only one variable, it is meaningless to define the struct. Note: In particular, do not forget to add a semicolon after the curly brace, because after all, the struct is a variable, and the definition of the variable is appended with a semicolon. As you can see, creating a custom variable is not complicated. In fact, the structure is a collection of various basic types of variables, a hodgepodge. Of course later in the course we will also see: The structure of the nested definition (structure contains another structure). The example of a struct assumes that we need to customize a struct that stores the coordinates of a point on the screen. A similar structure is used in the third part of "Writing games in C". The following gives the approximate impression that 2D (d is the first letter of the English dimension, which represents the dimension) of the world's coordinate system: 0 when we do research in the 2D world, we have two axes: the horizontal axis (from left to right, generally called the X axis) and the ordinate axis (from bottom to top, generally called the y axis). As long as the mathematics has not yet returned to the primary school chemistry teacher, should all know the x and the Y axis. Now, can you write the definition of a struct named coordinate (the meaning of English "coordinates")? I'll watch you! You can write your own first, then the reference we give: struct coordinate{int x;//horizontal axis int y;//ordinate}; Our coordinate this struct contains two variables: X and y, all int types, Represents the horizontal and vertical values, respectively. Of course, if we want to, you can also create a struct that represents a point of 3D (three-dimensional) space, just the COordinate This structure is based on the z axis. Arrays can also be stored inside an array structure inside a struct. You can construct a struct named person (the meaning of English "man"), as follows: struct Person{char firstname[100];//char lastname[100];///char address[1000];// address int age; Age int boy; Boolean values: 1 = Boy (boys), 0 = Girl (girl)}; As you can see, this struct variable contains five basic variables. The first three names, first names, and addresses, respectively, are character arrays. The fourth is the age, the fifth is a "boolean" (of course, the C language itself does not define a Boolean type (TRUE or false), but can be used to "denote" the Boolean value of the true or false), boy, the value of the int variable is 1, that is, for boys, if 0, that is the girl. This structure can be used to build an address book program. Of course, you can add other variables to the structure to make it more perfect. There is no limit to the number of variables in a struct. Structure use now that our structure is defined in the. h header file, we can use these constructs in the file containing the header file. The following shows how to create a variable of type coordinate (which we have defined above, which represents the coordinates of a two-dimensional space): #include "main.h"//contains the header file that defines the structure of the body int main (int argc, char *argv[]) { struct coordinate point; Create a variable of type coordinate, whose name is point (meaning of English "dot") return 0; As above, we have created a variable of type coordinate, named point. This variable automatically has two sub-variables: x and y, all int types, representing the horizontal and vertical values of this two-dimensional coordinate. You may want to ask: "Is it necessary to create the key struct at the beginning of the struct variable?" "Yes, it must." "Love me, not you ..." I'm sorry to digress ... The struct keyword enables the computer to differentiate between the underlying variable type (for example, int) and the custom variable type (for example, coordinate). However, each time the addition of the struct keyword is also a bit troublesome, so the wise (lazy) Ling (li) Li (c) of the language developers have designed the TypeDef keyword. Of course, most of mankind's inventions are for the sake of "laziness", can improve efficiency who do not want AH. This is the feel, the double-cool son. TyPedef the keyword back to the. h header file that you just defined coordinate the struct. Let's add a command that starts with a typedef to create an alias for the coordinate struct. What is an alias? For example, there is a person, the real name is Wang Xiaoming, the alias can be xiaoming, obviously, and so on, but all represent that person. A bit like the mechanism of C + + reference. So the operation of the alias is the operation of the original object. We will add this command before the definition of coordinate structure, the general habit is added in the back, but add in front can also: typedef struct coordinate coordinate;struct coordinate{int x;int y;}; As you can see, we've added a new line of commands: typedef struct coordinate coordinate; to better understand the role of this command, we split it into three parts: 1. typedef: Description We are going to create an alias 2. struct coordinate: This is the struct 3 for which we want to create an alias. Coordinate: This is the alias so, the meaning of the above command is "from now on, coordinate is equivalent to the struct coordinate". When we do this, we can not add the struct keyword every time we create a variable for a new coordinate struct. So, our. c file can be rewritten as: int main (int argc, char *argv[]) {coordonnees point;//Because with TypeDef, the computer knows clearly that the coordinate here is actually "struct Coordinate "return 0;} Of course, not necessarily called coordinate, alias can also be called: Coor. For example: typedef struct coordinate coor;struct coordinate{int x;int y;}; Coor Coor; Create a variable it is recommended that you also add a typdedef command after you define a struct type, so that you do not have to write the struct keyword at the beginning of each new variable of this type. A lot of programmers would do this. Because a good programmer is a programmer who knows how to be lazy, this is different from a lazy programmer. We're going to make our code "write Less,do More" (do more with as little code as possible). Of course, the code block above can be abbreviated as: typedef struct NAME {The contents of the struct} alias, so the above coordinate code block can be abbreviated as: typedef struct coordinate{int x;int y;} coordinate; Note: After our example code, sometimes it will appear for example person player1; coordinate point1; In this form, it is assumed that we have already used a typedef: typedef struct person person; You can omit the struct keyword from the beginning and do not need to write: struct person Player1 modifying a struct's member variable since our point variable (which is the coordinate type, hopefully everyone is not dizzy) has been created, then we can modify its member values. How do we access the two members of point X and y? as follows: int main (int argc, char *argv[]) {coordinate point;point.x = 10;point.y = 20;return 0;} In this way, we have successfully modified the value of the two member of point so that its x coordinate is 10,y coordinates of 20. So our point is in the coordinate system (10,20). So, in order to have access to a member of the struct, we can do this: struct instance name. The point (.) in the middle of the member name represents a "dependent" relationship. If you have a friend on the basis of object-oriented programming, you will feel that this is too similar to "classes and objects", yes, we can actually use structs to "emulate" classes. If we use the structure of the person we created above for example: int main (int argc, char *argv[]) {people user;//user is the meaning of English "users" printf ("What's your last name?"); scanf ("%s", User.lastname);p rintf ("What's your Name?"); scanf ("%s", User.firstname);p rintf ("Original your name is%s%s, forgive me forgive me \ n", User.lastname, User.firstname); return 0;} Run output: What's your last name? What's your name, Wang? Xiaoming originally your name is Wang Xiaoming, forgive me forgive me. We pass the user.lastname to scanf, which allows the user to enter values directly to modify the members of the LastName, as is the case with User.firstname. Of course, we can also add the Address,age,boyAssigned value. But small, lazy, will not continue. Being a programmer is going to be lazy. Of course, you might say, "I don't know about the use of structs, I use two separate string variables LastName and FirstName can do the same thing as the above procedure?" "Yes, but the advantage of using structs is that we can create variables for this struct, encapsulate many of the associated data together, become a whole, not a piecemeal definition." For example, after defining the structure of person, all variables created with person are automatically included in the five variables of lastname,firstname,address,age and boy, which is very convenient. For example we can create this: person Player1, player2; The typedef must have been useful before, (typedef struct person person;) Player1 and player2 contain the five variables of lastname,firstname,address,age and boy. We can also be more "lazy" some: to create an array of structural bodies. For example: Person player[2], so that we can easily access the variables in the player[1], for example: Player[1].lastname = "xiaoming"; the advantage of using a struct array is that loops can be easily used, and so on. Self-Test exercise: Create a struct called Programmerleague (programmer Union) and put the variables you want to create in the definition. It then creates an array of the struct, assigns the variable in a circular way, and then prints out the information of the variable in a circular way. Before the initialization of the struct, we recommend that for basic variables, arrays, and pointers, it is best to initialize them when they are created. Structural bodies are no exception. One of the great benefits of initializing is to avoid storing "arbitrary data" in this variable. In fact, when a variable is created, if it is not initialized, it takes the value stored at that point in memory, so the randomness of this value is very large. Let's recall how the initialization of different variables should be done: base variables (Int,double,char, etc.): initialized to 0 pointers: initialized to null. In fact, NULL is located in the Stdlib.h standard library header file and is a constant defined with the # define preprocessing command. It usually has a value of 0. Although it is 0, there are several defining forms, such as: #define NULL 0#define null 0l#define null ((void *) 0) But all we have to do is use null each time, to make it clear that this is a pointer variable, not a generic variable. Arrays: Initializes each member variable to 0 for our friendsFriend: struct, how do we initialize it? In fact, the initialization of the struct is also very simple, similar to the initialization of the array. We can define this as follows: Coordinate point = {0, 0}, so we initialize Point.x and Point.y to 0 in order. For a struct like person, where the variable type has a char array and an int, we can initialize the char array to "" (the middle of the double quotation marks is empty). We can initialize a string like this, forgetting to mention the previous "string" lesson. But I think it's not too late to mention it. So we can initialize our person struct variable: person player = {"", "" "" "", 0, 0}; However, we can also initialize a struct variable. Creating a function, such as initializestruct, can be initialized for each struct passed to it, which is much more convenient, especially if there are many variables in the struct. In the previous chapter of the pointer we have also learned that if we pass a normal variable to a function, then because the function parameter of C is passed as a value, it will make a copy of the function parameter passed to it, so the function modifies the copy, and the real argument is not changed. In order for the argument to be actually modified, we need to use the pointer, which is the address of the variable passed. This is also required for structs. So then we'll learn how to use struct pointers. It's going to be a little difficult at first. You ready? The creation of pointers to struct pointers is no different from normal pointer variable creation. For example: coordinate *point = NULL; The above code creates a coordinate struct pointer variable called point (coordinate is a struct of the representation coordinates we have defined above). Let's remind you again: The general recommendation is written as: coordinate *point = NULL; The asterisk is next to the pointer variable name and is not recommended as: coordinate* point = NULL; The asterisk is next to the struct name in the creation of the pointer, we recommend the first one, because if you create several pointer variables on a line in the second notation, it is easy to forget to precede the second variable with the * number. For example, it is easy to write like this: coordinate* point1 = null, Point2 = NULL, but this compiles an error because point2 is actually coordinate struct variable, not coordinate struct pointer variable! So we propose to write this: coordinate *point1 = NULL, *poiNt2 = null; In the previous lesson, we suggested that for pointer variables of the underlying type: int *number1 = NULL, *number2 = NULL, especially the int type pointer, it is not easy to detect errors, if written: int* number1 = NU LL, number2 = NULL; the compiler will not error. Because the null value is 0, you can assign the NUMBER2 int variable (NOTE: The above number2 is not an int pointer). Well, the review is always good, (sad is always inevitable ...) )。 struct as a function parameter here, we mainly learn how to pass a struct pointer (why a struct pointer rather than a struct) to a function (as an argument), so that the structure can be really modified inside the function. Let's look at an example: #include typedef struct coordinate//coordinate is the meaning of English "coordinates" {int x;//horizontal axis value int y;//Ordinate value} coordinate;void initializestruct (coordi Nate *point); function prototype int main (int argc, char *argv[]) {coordinate mypoint; initializecoordinate (&mypoint); return 0;} Used to initialize struct variable void initializecoordinate (coordinate *point) {//Drop struct initialization code} above the Initializecoordinate function body, We will place the code that initializes the member variables of the struct. Let's take a look at this code in order: first, we define a struct, called coordinate, which contains two variables, x and Y. In the main function, we created the variable of the coordinate struct, called mypoint. We pass the MyPoint address to the Initializecoordinate function. Next, we'll add the code to initialize the x and Y variables in the initializecoordinate function: void initializecoordinate (coordinate *point) {*point.x = 0; *point.y = 0 ;} The * number in front of point is not very small, oh, because the argument to the function is a struct pointer, we want to take this struct, we need to use the "dereference" symbol: * number. But do serious readers see the error in the above function? Our intention is to: first Use the * number to refer to the struct pointer of point, take the struct, and then use the. Number to which the variable x and y are taken. But if you follow the above, the effect is equivalent to the following: * (point.x) = 0;* (POINT.Y) = 0; The priority of the. Number is higher than the * number. It's interesting to take a look at the precedence of operators, but we've said that before, what do we do? The parentheses will solve the problem. The above code compilation is not possible, because the struct pointer point has no members called X and Y, and we cannot use the. Number to fetch any value for the struct pointer. Therefore, we need to revise it. Change to the following: void initializecoordinate (Coordinate *point) {(*point). x = 0; (*point). y = 0;} That's right. The effect of operator precedence is removed with parentheses. But, as I said before, programmers are a bunch of people who know how to be lazy. If every time you want to take the structure of the member variable to be so troublesome, to use the * number, but also parentheses, and then use. Think of all to let Denis Ritchie the Don drunk. He would never allow such a thing to happen, so he defined a new symbol: The usage is as follows: point->x = 0; it is equivalent to: (*point). x = 0; Is it a lot easier? Remember: This symbol is used only on the pointer. Therefore, our function can be rewritten as: void initializecoordinate (coordinate *point) {point->x = 0; point->y = 0;} We can also write this in the main function: int main (int argc, char *argv[]) {coordinate mypoint; Coordinate *mypointpointer = &myPoint; Mypoint.x = 10; Modify the X-value mypointpointer->y = 15 in the MyPoint in the form of a struct; Modify the Y value in the mypoint with the struct pointer to return 0;} Structure is a C language in a very useful, very important concept, I hope you have a good grasp, of course, there are a lot of knowledge of the details of the C language to see the classic textbooks, such as "C programming language" (not rectification "C language Programming"), "C and Hands", "c expert programming", " Deep anatomy of C language, C pitfalls and defects, etc. Unionunion is the term "union" meaning, is the C language of the keyword, but also some books translated as "Common body." We can write an example of union. Union Programmerleague{char character;int membernumber;double rate;}; At first glance, it's no different from struct. But is there really no difference? If we use the sizeof keyword to test the size of this Union (size refers to the number of bytes (byte) it occupies in memory, one byte is equivalent to 8 bit (bits)): #include typedef union programmerleague{char character;//size is 1 int membernumber;//size is 4 double rate;//size is 8} programmerleague; int main (int argc, char *argv[]) {programmerleague programmerleague; printf ("The size of this union is%lu\n", sizeof (Programmerleague)); return 0;} Run program, output: The size of this Union is 8 if we do a test on the structure, compare: #include typedef struct programmerleague{char character;//size is 1 int membernumber;//size is 4 double rate;//size is 8} programmerleague ; int main (int argc, char *argv[]) {programmerleague programmerleague; printf ("Size of this struct is%lu\n", sizeof (Programmerleague) ); return 0;} Run program, output: The size of this structure is 16 why one is 8 and the other is 16? This involves the difference between a union (a common body) and a struct (struct). The size of the struct is the sum of all the variable sizes, but you'll say, "no, 1+4+8 = 13, why is sizeof (Programmerleague) a value of 16?" "Good question!" This is a bit complicated and involves memory alignment issues that we'll talk about later. Or interested readers can refer to the "C-Language Deep anatomy" (online can be found in pdf) interpretation. The General Beginner C language does not need to delve into this problem too much. In memory-constrained environments such as embedded programming, memory alignment needs to be considered to save space. The size of the Union is equal to the size of the variable with the largest (sizeof () maximum). So we know, in fact, the union storage is this: each variable in the memory of the starting address is the same, so the Union can only hold one of the variables at the same time, so the size of the Union is equal to the largest of the variables, to ensure that any member can be accommodated. Union is suitable for many sets of variables of the same type, but only one of them can be used at a time to save space. Enum after reading the struct (struct) and Union (union), we end up learning a very common custom variable type: enum. An enum is an abbreviation for English enumeration (enumeration) and is also a C keyword. Enumerations are a special type of custom variables. When I first learned C, it was a bit of a misunderstanding. But it's good, but it's very practical. We learned before: structs contain multiple member variables that can be of different types (a "member" is a bit of an object-oriented feeling:P. Articulation to clear, not "Chun Yuan" queen that one yuan, is a member. Small make up you so naughty not ah ... )。 But an enum (enum) is a series of selectable values. That means you can only take one of these values at a time, and listen to a bit like union. But there's a difference with union.Of Let's give an example to know the difference: TypeDef enum SHAPE Shape;enum shape//shape is English "figure, body shape" meaning {THIN,//THIN is English "thin" meaning MEDIUM,//MEDIUM is English "medium" Meaning fat/fat is English "fat" meaning}; So, we define an enum variable called shape. There are three values, namely, thin, medium and fat (stature has thin, medium and fat points). Not necessarily uppercase, just habit. So how do we create an enum variable? As follows: Shape shape = medium;shape This variable, we can also change it to thin or fat in the program. Assigning values to members of an enum do you see the difference between the enum and the Union and the struct? Yes, in the definition of enum, each member has no variable type (int,char,double, etc.)! It's strange. Remember why the members of the enum are used to capitalizing? Yes, because every member of the enum is not a variable, but a constant. But there are some differences between the mechanism of enum and the definition of constants and # define: Like the code above: typedef enum shape{THIN, MEDIUM, FAT} Shape; The compiler automatically binds each member to a constant value, and we write the program to test it: # Include typedef enum SHAPE Shape;enum shape{THIN, MEDIUM, fat};int main (int argc, char *argv[]) {shape shape = THIN; printf ("THI N =%d\n ", shape); shape = MEDIUM; printf ("MEDIUM =%d\n", shape); shape = FAT; printf ("FAT =%d\n", shape); return 0;} Run program, output: THIN = 0MEDIUM = 1FAT = 2 See? The compiler automatically assigns 0, 1, and 2 to these three members. If you do not specify the values of the enum member, then their values are 0, plus 1. We can also define the values of the enum members ourselves, not necessarily each time the compiler assigns it to us automatically. We can write this: typedef enum shape{THIN = +, MEDIUM = $, FAT = n} Shape, so we define values for each member ourselves. We can also let the compiler automatically assign several values to us, and then define several values ourselves, such as typedef enum shape{THIN, MEDIUM, FAT = n} Shape; above, we do not assign values for THIN and MEDIUM, Then the compiler assigns them a value of 0 and 1, and fat, because we have specified a value of 90, so fat equals 90. Does the difference between enum and # define mean that enums and constants defined by # define are somewhat similar? In fact, there are some differences: #define Macro Constants (or preprocessing constants) are simple replacements during the preprocessing phase, while enumeration constants determine their values at compile time. Typically in the compiler, you can debug enumeration constants, but you cannot debug macro constants. Enumerations can define a large number of related constants at once, and a # define macro can only define one at a time. The summary structure (struct) is a kind of custom variable type, completely by our free play, custom-made by ourselves. differs from base variable types such as int,double. The use of structs can make our C language programs more flexible and can do more. A struct contains member variables, usually variables of the underlying variable type, such as variables such as int,double, but can also have pointer variables, arrays, and even other struct variables. In order to access the member variables of the struct, we can access the struct variable name in the normal way. Member Variable name we can also use a particularly simple structure pointer to our structureMember variables of the body: struct pointer variable name, member variable name Union ("Common body", or "union") and struct are the most different: the size of the union is the size of the member variable with the largest capacity. The size of the struct is the sum of each member variable (and also the memory alignment), and the Union can only take one of the variables at a time. An enum (enum) can only take the value of one of these members at a time, which is somewhat similar to union, but the members of the enum are constants, not variables. And if the members of the enum do not specify a numeric value, the compiler assigns values to each variable in ascending order, starting with 0. The second part of the seventh lesson Notice: Today's lesson on here, together refueling. Next time we study: file reading and writing Programmer Alliance Community currently has a group and a QQ group (group of more than 120 people, QQ group of more than 250 people), all interested in programming friends can add, we can exchange, study, interaction, discuss the source code of writing programs, programming questions and so on. How to "Scan" the QR code image on the phone? Tips: In the long press the picture, select "Identify the QR code", you can group (Programmer Alliance), Dabigatran please private messages Me (group of more than 100, can not scan the QR code to join, only private messages I, thank you) QQ Group (Programmer Alliance), group number is There are n multi-programming PDFs in the 413981577QQ group share. Scan the following two-dimensional code plus QQ Group: 0 We also set up a public Baidu cloud disk, 2TB capacity, for everyone to upload excellent programming resources, link Dabigatran will be sent. Also created the "Alliance of Programmers" micro-community, easy to ask questions and interaction. Can take a look. Micro-Community address and QR code are as follows: http://m.wsq.qq.com/2641521480 Thank you! 0 Programmer's Union public number * If you think this article is good, please click on the top right corner of the screen "... Button "Share to Friends" or "Send to a friend" * New friends Please pay attention to "the Programmer Alliance" search public number Programmerleague small number: Frogoscar Small series QQ number: 379641629 Small Series e-mail: [email protected] Programmer Alliance QQ Group: 413981577 Programmer Alliance Group: first plus I have friends to reflect on the mobile phone end of the article is too tired, in fact, can be viewed in a browser Web page Method 1. In the top right corner of the screen, click the ... button, then select "Copy Link", then paste the link into your browser or email it to yourself, you can open the 0 method 2 in the browser of the computer. Headline net www.toutiao.com, search my self-media "programmer alliance", there are all articles, you can also directly into this link: http://www.toutiao.com/m3750422747/Method 3. My 51CTO Blog and cSDN Blog Link (all articles will be on it) Http://4526621.blog.51cto.com/http://blog.csdn.net/frogoscar new friends How to view all articles: Click on "View public number" and click "View History Message" 00 the "Programmer Alliance" public number is designed for programmers, app designers, people who love to program and share the small partners to push all kinds of programming knowledge, excellent software recommendations, industry trends and so on. Search Programmerleague + Attention ~ click "Accessories" below to view Dennis Ritchie "C Programming Language" Second edition of the Chinese version pdf↓↓↓
C Language Discovery Tour Part VI lesson: Creating your own variable types