introduction
C is a strongly typed language, and data types are the basis of programming. Understanding variables, constants, data type keywords in C language and how to use these data types is the key to mastering C language programming.
1. Variables and constants
1.1 Variables
Variables are containers used in programs to store data. Variables need to be declared first and then used, and the data type needs to be specified when declaring.
grammar:
Data type Variable name;
Example:
int age; // Declare an integer variablefloat salary; // Declare a floating point variablechar grade; // Declare a character variable
1.2 Constants
Constants are fixed values in the program. Constants can be literals (eg
10
、3.14
), can also be used#define
orconst
Keyword definition.grammar:
#define Constant Name Valueconst Data Type Constant name = value;
Example:
#define PI 3.14159 // Use #define to define constantsconst int MAX_SCORE = 100; // useconstDefine constants
2. Data type keywords
C language provides a variety of data type keywords to define different types of data. The following are the basic data type keywords in C language:
Data type keyword descriptionint
Integer (integer)float
Single-precision floating point type (decimal)double
Double precision floating point type (higher precision decimal)char
Character type (single character)void
No type (usually used for function return value)
Data type keywords | describe |
---|---|
int |
Integer (integer) |
float |
Single-precision floating point type (decimal) |
double |
Double precision floating point type (higher precision decimal) |
char |
Character type (single character) |
void |
No type (usually used for function return value) |
3. Basic data types in C language
3.1 Int
In C language,
int
is a basic data type used to define integer variables.
3.1.1 Definition and Meaning
int
It is the abbreviation of "integer" (integer), which declares that a variable can store integer values. These integers include positive integers, negative integers, and zeros, e.g.1
、-5
、0
wait.
3.1.2 Memory usage and value range
In different C language implementations and different operating system environments,
int
The memory space and range of values occupied by a type may vary, but usually,int
Type occupies 4 bytes (32-bit) of memory space in a 32-bit system. The range of values is generally from-2^31
arrive2^31 - 1
, that is,-2147483648
arrive2147483647
。
3.1.3 Declaration and Initialization
-
statement:statement
int
The general form of integer variables isint variable name;
. For example,int num;
Declare a name callednum
ofint
Type variable. -
initialization: You can initialize the variable while declaring it, that is, give it an initial value. For example,
int num = 10;
Declare a name callednum
ofint
type variable and initialize it to10
. You can also declare it first and then initialize it, such asint num; num = 10;
。
3.1.4 Operation
int
Integer variables can participate in various mathematical operations, such as addition (+
), subtraction (-
),multiplication(*
),division(/
) and take the remainder (%
) and other operations.Special attention: In division operation, if both operands are integers, the result will be integers and the decimal part will be discarded. like
5 / 2
The result is2
, not2.5
。For example:
#include <> int main() { // Define two integer variables a and b and initialize them to 10 and 3 respectively int a = 10; int b = 3; // Perform addition operations and store the result in the sum variable int sum = a + b; // Perform subtraction operations and store the result in the difference variable int difference = a - b; // Perform multiplication operation and store the result in the product variable int product = a * b; // Perform division operation and store the result in the quotient variable // Note: Since a and b are both integers, the division result will discard the fractional part int quotient = a / b; // Perform the remaining operation and store the result in the remainder variable int remainder = a % b; // Output the result of the addition operation printf("and: %d\n", sum); // Output the result of the subtraction operation printf("Difference: %d\n", difference); // Output the result of multiplication operation printf("Auto: %d\n", product); // Output the result of division operation printf("Trade: %d\n", quotient); // Output the result of the remaining operation printf("Remaining: %d\n", remainder); // Return to 0 means that the program ends normally return 0; }
3.1.5 Practical application scenarios
int
Integer variables are very common in C programming and are widely used in various scenarios. For example, it is used for counting, such as a counter in a loop controlling the number of cycles; it represents the subscript of an array, used to access elements in the array; it stores and processes data of various integer values, such as age, number of people, student numbers, etc.For example:
#include <> int main() { // Define an integer variable age to represent age and initialize it to 25 int age = 25; // Define an integer variable classSize to represent the number of students in the class and initialize it to 30 int classSize = 30; // Output age information printf("Age: %d years old\n", age); // Output class number information printf("Class number: %d person\n", classSize); // Use for loop to traverse every student in the class // Loop variable i starts at 0, incrementing 1 each time until i is less than classSize for (int i = 0; i < classSize; i++) { // Output the student number of each student // Since student ID usually starts from 1, use i + 1 as student ID printf("Student number: %d\n", i + 1); } // Return to 0 means that the program ends normally return 0; }
3.2 Float and double
In C language, floating-point variables are used to store numeric values with decimal parts, that is, real numbers.
3.2.1 Definition and Meaning
Floating point type is a data type that can represent the value containing the decimal part. In practical applications, we often need to deal with non-integer values like 3.14 and 0.001, and then floating-point variables will be used. C language provides two main floating-point data types:
float
(Single precision floating point type) anddouble
(Double precision floating point type).
3.2.2 Memory usage and value range
-
float
: Usually takes up 4 bytes (32 bits) in memory. It can represent approximately 6 to 7 significant digits, with a value range of approximately ±1.18×10⁻³⁸ to ±3.40×10³⁸. -
double
: Generally occupies 8 bytes (64-bit) of memory space. It can represent about 15 to 16 significant digits, with a value range ratiofloat
Big, about ±2.23×10⁻³⁰⁸ to ±1.80×10³⁰⁸.
3.2.3 Declaration and Initialization
- statement:
- Declares the float type variable in general form as the float variable name;. For example, float num; declares a float type variable named num.
- Declare the general form of a double type variable is the double variable name;. For example, double d_num; declares a double type variable named d_num.
- initialization:
- Variables can be initialized while declaring them. For float type, f or F should be added after the initialization constant, such as float num = 3.14f; for double type, directly assign values, such as double d_num = 3.14159;. You can also declare it first and then initialize it, such as float num; num = 3.14f; and double d_num; d_num = 3.14159;.
3.2.4 Operation
Floating point variables can participate in various mathematical operations, such as addition (
+
), subtraction (-
),multiplication(*
),division(/
) and other operations.For example:
#include <> int main() { // Define two single-precision floating-point variables a and b, and initialize them to 3.14 and 2.71 respectively float a = 3.14f; float b = 2.71f; // Perform addition operations and store the result in the sum variable float sum = a + b; // Perform subtraction operations and store the result in the difference variable float difference = a - b; // Perform multiplication operation and store the result in the product variable float product = a * b; // Perform division operation and store the result in the quotient variable float quotient = a / b; // Output the result of the addition operation, retaining two decimal places printf("and: %.2f\n", sum); // Output the result of the subtraction operation, retaining two decimal places printf("Poor: %.2f\n", difference); // Output the result of the multiplication operation, retaining two decimal places printf("Amount: %.2f\n", product); // Output the result of the division operation, retaining two decimal places printf("Trade: %.2f\n", quotient); // Return to 0 means that the program ends normally return 0; }
In the above code, use
%.2f
Format the output result and retain two decimal places.
3.2.5 Practical application scenarios
Floating point variables are also very common in C programming and are widely used in various scenarios where decimals are required. For example, it is used for scientific calculations, such as calculations in physical formulas; it represents the amount of money; it represents coordinates, angles, etc. in graphical processing.
#include <> int main() { // Define a single-precision floating-point variable price to represent the price of the product, with an initial value of 9.99 yuan float price = 9.99f; // Define a single-precision floating-point variable pi to represent pi, with an initial value of 3.14159 float pi = 3.14159f; // Define a single-precision floating-point variable radius to represent the radius of the circle, with an initial value of 5.0 float radius = 5.0f; // Calculate the area of the circle according to the area formula S = π * r * r, and store the result in the area variable float area = pi * radius * radius; // Export the price of the product, keep two decimal places printf("Product price: %.2f yuan\n", price); // The radius and corresponding area of the output circle are retained in two decimal places. printf("Area of a circle with a radius of %.2f: %.2f\n", radius, area); // Return to 0 means that the program ends normally return 0; }
In this example, use
float
Type variables represent the commodity price, pi and radius, and calculate the area of the circle, and finally output relevant information.
3.3 Character type (char)
In C language,
char
is a basic data type used to define character variables.
3.3.1 Definition and Meaning
char
is the abbreviation of "character" (character), used to declare that a variable can store a single character. In computers, characters are stored in the form of corresponding ASCII code values (or other character encodings, such as Unicode). therefore,char
The type is essentially an integer type that can store a byte (8 bits) of data, usually in the range of -128 to 127 (signedchar
) or 0 to 255 (unsignedchar
), which depends on the compiler implementation. Common characters such as letters ('A'
,'a'
),number('0'
,'9'
), punctuation marks (','
,'.'
) etc. can be usedchar
Type to represent.
3.3.2 Memory usage and value range
-
Memory usage:
char
Types usually occupy 1 byte (8 bits) of memory space. -
Value range:
-
Signed
char
: Range is -128 to 127. Can be usedsigned char
Explanatory declaration of signed character types, but it is generally used directlychar
When , the default is signed (depending on the compiler). -
Unsigned
char
: The range is 0 to 255, useunsigned char
Let’s declare.
-
Signed
3.3.3 Declaration and Initialization
-
statement: Statement
char
The general form of type variables ischar variable name;
. For example,char ch;
Declare a name calledch
ofchar
Type variable. -
initialization: You can initialize the variable while declaring it, that is, give it a character constant. Character constants are single characters enclosed in single quotes, for example
'A'
、'5'
wait. Examples are as follows:
char ch = 'A'; // Declare and initialize a char Type variable ch,Its value is a character 'A'
You can also declare it first and then initialize it, such as:
char ch; ch = 'B'; // Statement first ch,Initialize it into a character 'B'
3.3.4 Operation
char
A type variable can participate in some operations because it is essentially an integer type. Common operations include:
-
Assignment operation: You can assign a character constant to
char
Type variables, as shown in the above example. - Arithmetic operations: Arithmetic operations such as addition and subtraction can be performed, and the operations will be based on the ASCII code value corresponding to the characters. For example:
#include <> int main() { char ch = 'A'; char new_ch = ch + 1; // Add 1 to the ASCII code value of the character 'A' printf("Original character: %c, new character: %c\n", ch, new_ch); return 0; }
In the above code, the characters'A'
The ASCII code value is 65, add 1 to get 66, and the corresponding character is'B'
, so the output result is the original character is'A'
, the new character is'B'
。
3.3.5 Practical application scenarios
char
Type variables are very common in C language programming and are widely used in various scenarios. for example:
-
Process text data: When processing strings, strings are actually composed of a series of
char
Array of characters of type. For example, the names, sentences, etc. entered by users are stored and processed. - Character judgment: You can judge based on the ASCII code value of the character, such as determining whether a character is a letter, a number, etc. The sample code is as follows:
#include <> int main() { char ch = 'a'; if (ch >= 'a' && ch <= 'z') { printf("%c is lowercase letter\n", ch); } else { printf("%c is not a lowercase letter\n", ch); } return 0; }
In this example, by comparing charactersch
The ASCII code value of determines whether it is a lowercase letter.
3.4 No type (void)
3.4.1 Definition and Meaning
In C language,
void
Not likeint
This is used to define ordinary variables.void
The literal meaning of type is "no type" or "empty type", which mainly has the following special uses:1. Function return type
When a function does not need to return any value, its return type can be declared as
void
. This indicates that the function performs a specific operation, but does not return a specific data to the caller.2. Function parameter list
When defining a function, if the function does not accept any parameters, the parameter list can be written as
void
. However, in modern C language, empty brackets can also be used directly.()
Come to express.3. General pointer type
void *
is a general pointer type that can point to any type of data. This pointer can store the address of any type of variable, but it usually requires explicit type conversion when used.
3.4.2 Performance in different scenarios
1. Return type as a function
#include <> // Define a function with a return type void to print a greetingvoid greet() { printf("Hello, World!\n"); } int main() { // Call greet function greet(); return 0; }
In this example,
greet
The return type of the function isvoid
, means it does not return any value, it just performs the operation of printing the greeting.2. As a function parameter list
#include <> // Define a function that does not accept any parameters, the parameter list uses voidvoid printMessage(void) { printf("This is a message.\n"); } int main() { // Call the printMessage function printMessage(); return 0; }
here
printMessage
The parameter list of the function isvoid
, means that the function does not accept any parameters.3. As a general pointer type
#include <> int main() { int num = 10; // Define a void pointer to a variable of type num void *ptr = &num; // Since the void pointer cannot be dereferenced directly, type conversion is required int *intPtr = (int *)ptr; printf("The value of num is: %d\n", *intPtr); return 0; }
In this code,
void *
Type pointerptr
Pointed to oneint
Type variablenum
. But becausevoid
Pointer cannot be dereferenced directly, so it needs to be converted toint *
After type pointer operation.
3.4.3 Notes
-
Can't be determinedrighteous
void
Type variables:becausevoid
means no type, so it cannot be likeint
Define one directlyvoid
Variables of type, such asvoid var;
Such code is illegal. -
void
Pointer needs to be converted when used: When usedvoid *
When dereferences or performing operations that require specific types, it must be converted to a suitable pointer type first.
Conclusion
The data types of C language are the basis of programming. Understanding variables, constants, data type keywords and how to use these data types is the key to mastering C language programming. Through the explanation and code examples of this article, I hope you can better understand the data types in C language and be able to flexibly use them to write high-quality code!
This is the end of this article about C data variables, constants, data types and usage examples. For more relevant C data variables and constants, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!