[C language exploration journey] Part 1 Lesson 4 Chapter 2: Variable Declaration of the world of variables Chapter 2
Introduction
1. Course outline
2. Part 1 Lesson 4 Chapter 2: Variable Declaration of the world of Variables
3. Part 1 Lesson 4 Chapter 3 Notice: DISPLAY variable content in the world of Variables
Course outline
Our courses are divided into four parts. Each part has exercise questions after completion and answers will be published. Three games will also be written in C language.
Basic knowledge of C Programming
What is programming?
To do their best, you must first sharpen your tools.
Your first program
World of Variables
Operator
Conditional expressions
Loop statement
Practice: The first C games
Function
Exercise questions
Exercise: Perfect the first C games
C Advanced Technology
Modular programming
Attack pointer, C trump card
Array
String
Preprocessing
Create your own variable type
File read/write
Dynamic Allocation
Practice: "hanging villain" games
Secure text input
Exercise questions
Exercise: Explain the pointer in your own language
Develop 2D games with C language-based SDL Library
Install SDL
Create a window and canvas
Show images
Event Processing
Practice: "Super Mary pushes boxes" games
Time usage
Use SDL_ttf to edit text
Use FMOD to control sound
Practice: Visual Sound line
Exercise questions
Data Structure
Linked List
Heap, stack, and queue
Hash table
Exercise questions
Part 1 Lesson 4 Chapter 1: Variable Declaration of the world of Variables
In the last lesson, we learned about memory in the variable world. Believe me, the last lesson is definitely useful for memory exploration. In this lesson, we will learn the declaration of variables.
What is a variable?
Simply put, a variable is a small piece of information temporarily stored in the memory.
Why is it called a Variable? The English language of the Variable is Variable, and the adjective is "Variable, easy to change". So the Variable is the amount of value that can be changed during the program running.
You will see that the program we write is often filled with variables.
In C language (as in most languages), a variable has two parts:
Variable value: the value stored in the variable, such as 5
Variable name: used to identify a variable. If you are a friend who has learned to worry about using the memory address value as a variable, do not worry. In C, we do not use the address value as the variable name, we only need to give it a name. The compiler will convert the name to the memory address value. Is it just a sigh of relief?
Name the variable
In C, each variable must have a name. We can't just get a name, but also observe some restrictions:
The following are some correct variable names:
Dog, cat_and_mouse, Catch_1_mouSe, hao123COM
Note that the C language is case sensitive. Therefore, hello and Hello are two different variable names.
Every programmer has the habit of naming variables. Let me talk about the variable naming habits of this course:
Variable names all start with lowercase letters
If the variable name is composed of several words, the first letter of the first word is in lowercase, and the first letter of other words is in uppercase.
I hope that you can maintain consistent naming conventions in subsequent exercise questions as much as possible (in fact, this is a general naming method ).
When naming a variable, try to make it clear and easy to understand. If I abbreviated a variable petName (pet name) as pN, although it is short and concise, the person who reads the Code cannot guess what it means. We should try our best to ensure that the code can be "self-Annotated". That is to say, simply looking at the variable name, we can know the purpose of the variable, and many times we can omit the annotation.
Variable type
Our computer brother is actually a stupid machine. He only knows the computation and can only process numbers.
However, there are many types of numbers in the C language:
Positive integers, such as, and
Contains a positive number of decimal points, such as 3.14159, 27.62, 80.19732
Negative integers, such as-7,-999,-4321
There is a negative number containing the decimal point, such as-6.753,-78.46,-5641.73
Why are there so many messy types? Poor computer guy needs help.
Therefore, when you want your computer to store a number, you need to provide the type. It does not mean that computers cannot be distinguished, but that they can be better planned for computers and not to occupy excess memory.
Therefore, in C language, when we declare a variable, the variable type must be given.
The following table lists the main types.
Type name |
Minimum value |
Maximum Value |
signed char
|
-127 |
127 |
int
|
-32 767 |
32 767 |
long
|
-2 147 483 647 |
2 147 483 647 |
float
|
-1x1037. |
1x1037 |
double
|
-1x1037. |
1x1037 |
The data listed above is the minimum value range guaranteed by the C language. Of course, you can declare a variable with a larger scope.
However, it is better to remember the values in the above table to help you select the variable type correctly.
Of course, there are other variable types in C language. The above table only lists commonly used variables.
All the variable types in C language are given below:
The first three types (signed char, int, long) in the preceding table are used to declare integers. For example, 6, 74, 8931, etc.
The latter two types (float and double) are used to declare floating point numbers (including the number of decimal points ). For example: 7.64, 61.467, etc.
In the subsequent courses, you will see that integers are used the most, because they are easy to use.
There are other types.
Let's talk about the difference between signed and unsigned: signed is signed, that is, the first positive or negative sign (positive or negative), such as 7,-5, 9.2,-23.8, and so on. Unsigned is an unsigned number. It can only be a positive number, such as 35, 7461, 61.789, and so on.
Therefore, signed int Is a signed integer and unsigned int Is an unsigned integer. And so on.
Put signed and unsigned in front of int, long, char, float, double, and other types.
unsigned char
|
0 à 255 |
unsigned int
|
0*65 535 |
unsigned long
|
0 à 4 294 967 295 |
In the above table, we can see that the unsigned type cannot store negative numbers, but the advantage of the signed type is that it can store twice the maximum value of the signed type. For example, the maximum value of signed char is 127, the maximum value of unsigned char is 255.
Why are three types of integers listed in the previous table: char, int, and long? Is it not enough?
Yes. The objective of creating multiple integer types in C language is to save memory. If we declare a char variable, the memory space used by the computer will be smaller than that of the int type.
Of course, in the age when the memory was very limited (ah, Yao Xiang Gong Jin, Xiao Qiao married...), multiple integer types were very useful. Today, our computer has a considerable amount of memory (all the way, a few character stream, but also look at the present), and generally no longer need to declare variables.
Make a summary:
For integers, int is generally used.
For floating point numbers, double is generally used.
Declare Variables
After so many preparations, we finally reached the topic of this chapter. Now, create a new console project named Variable.
Let's learn how to declare variables, that is, to request the computer to allocate some memory space for us to use.
Declaring variables is actually very simple. You should know how to do it. You only need to follow the following sequence:
Write the type of the variable we want to create
Kong Ge
Write your name for the variable
Finally, do not forget to add a semicolon
For example, I can declare some variables like this.
Int growthOfEconomy;
Double averageSalary;
Unsigned int numberOfDogs
The above is called a variable declaration. Remember this term. You should declare the variable at the beginning of the function. Now that we only have one function: main function, we declare a variable as follows:
# Include <stdio. h>
# Include <stdlib. h>
Int main (int argc, char * argv [])
{
Int numberOfDogs;
Return 0;
}
If you run the above program, you will be surprised to find that this program seems to have nothing to do.
Some explanations
Well, before you accuse me of deceiving you, let me justify it:
In fact, this program does something, but you can't see it. When the program reads the variable declaration line, it politely asks the computer if it can use some memory space.
If everything goes well, the computer will answer "okay, no problem. Take some memory space ". In general, it will go smoothly. Therefore, your variables are generally created (unless the memory is insufficient, but this rarely happens, because you only need to allocate an int space, and there is very little space.
A small "trick": If you have several variables of the same type to declare, there is no need to write a row for each variable declaration, you can write them on one line, for example:
Int numberOfDogs, numberOfCats, numberOfMouses;
Three int-type variables are declared at the same time: numberOfDogs, numberOfCats, and numberOfMouses.
What then?
Now that we have declared the variable, we can assign a value to the variable.
Nothing is simpler than this. If you want to assign values to the numberOfDogs variable
NumberOfDogs = 7;
You don't have to do anything else. Enter the variable name, an equal sign, and the value you want to give it.
Above, we just assigned 7 to numberOfDogs (number of dogs ).
Therefore, our complete program is now like this:
# Include <stdio. h>
# Include <stdlib. h>
Int main (int argc, char * argv [])
{
Int numberOfDogs;
NumberOfDogs = 7; // There are seven dogs
Return 0;
}
If you run it this time, nothing will happen and nothing will be displayed on the screen. But in fact, everything is quietly in the memory, but you can't see it.
Somewhere in the depths of your computer, a small block of memory has just stored the value 7. Is it amazing?
We can try to change the value of the variable, such:
Int numberOfDogs;
NumberOfDogs = 7;
NumberOfDogs = 6;
NumberOfDogs = 5;
In the preceding example, the int type numberOfDogs variable is first assigned 7, then changed to 6, and then to 5. Because your computer's computation speed is too fast, this series of operations are completed in an instant. Before blinking, the value of your variable numberOfDogs changes from 7 to 6 and then to 5.
New variable value
Now let's look at a very important question:
What is the initial value of a variable when we declare it?
In fact, when the computer reads this line:
Int numberOfDogs;
First, it takes a small block in the memory for numberOfDogs. But what is the value of numberOfDogs? Is there a default value (for example, 0?
The answer is: no.
No default value. In fact, numberOfDogs is given to this small area of memory, but the above value has not changed, and we have not cleared the original value on this small area of memory. Therefore, the initial value of your variable numberOfDogs is the value in that small memory. This value can be arbitrary.
If the memory value has not changed before, it may be 0.
You are not sure. The initial value may be 45 or 182, because a program may have changed the value on that address.
So be careful. The best solution is to assign an initial value to the variable when you declare it:
Int numberOfDogs = 7;
Here, the int variable numberOfDogs is declared and immediately assigned to 7.
The advantage is that you can determine the value of this variable, instead of any number.
Const keyword
Sometimes we want to use a variable, and we want its value to remain unchanged in the program. That is to say, once declared, you want your variable to keep its initial value, and no one can change it.
This special variable is called a constant (constant, unchanged) variable and is modified by the const keyword.
Some books say that const modifies constants and is inaccurate. The const modifier is a variable, but a read-only variable, because after the const is added, the value cannot be changed.
How to declare a constant variable? Simple:
You only need to place the const keyword before the type of your variable (which can be placed later). In addition, when declaring the constant variable, you must assign the initial value to it!
For example:
Const int NOMBBER_OF_DOGS = 7;
The name of the const variable must not be capitalized, but is generally capitalized.
Except that the value cannot be changed, the const variable is the same as the general variable. However, if you want to change the value of the const variable in a later program, the compiler will prompt an error, for example:
[Warning] assignment of read-only variable 'nombber _ OF_DOGS'
(Warning: try to change the value of the read-only variable NOMBBER_OF_DOGS)
Part 1 Lesson 4 Chapter 2 Notice: DISPLAY variable content in the world of Variables
Today's class is here. Come on together.
In the next lesson, we will continue to explore the fantastic world of C language variables.
Programmer Alliance public account* If you think this article is good, click "share to friends" or "send to friends" or "add to Favorites" in the upper-right corner of the screen"
* New friends should follow the "Programmer alliance" Search Public AccountProgrammerleleague
Little Editor: frogoscar
Mini-editor's QQ number: 379641629
Small mailbox: enmingx@gmail.com
(Most common with mailbox)
PS: A friend reported that reading articles on the mobile phone is too tired. In fact, they can be viewed on a browser webpage.
Method 1. click the "·" button in the upper-right corner of the screen, select "Copy link", paste the link to your browser, or send it to yourself by email, you can open it in your computer's browser.
Method 2. toutiao.comWww.toutiao.com, Search my self-Media "Programmer alliance", which has an article, you can also directly into this link: http://www.toutiao.com/m3750422747/
How do new friends view all articles:
Click "view public account" and then "view historical messages"
The "Programmer alliance" public account is designed for programmers and App designers. You love programming and sharing to push a wide range of programming-related knowledge, excellent software recommendations, and industry trends. Search for ProgrammerLeague and follow-up ~
Continuous attentionProgrammer AlliancePublic Account, more interesting, expected, and content with highlights are waiting for you!